bytereader.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2019+ Klaus Post. All rights reserved.
  2. // License information can be found in the LICENSE file.
  3. // Based on work by Yann Collet, released under BSD License.
  4. package zstd
  5. // byteReader provides a byte reader that reads
  6. // little endian values from a byte stream.
  7. // The input stream is manually advanced.
  8. // The reader performs no bounds checks.
  9. type byteReader struct {
  10. b []byte
  11. off int
  12. }
  13. // advance the stream b n bytes.
  14. func (b *byteReader) advance(n uint) {
  15. b.off += int(n)
  16. }
  17. // overread returns whether we have advanced too far.
  18. func (b *byteReader) overread() bool {
  19. return b.off > len(b.b)
  20. }
  21. // Int32 returns a little endian int32 starting at current offset.
  22. func (b byteReader) Int32() int32 {
  23. b2 := b.b[b.off:]
  24. b2 = b2[:4]
  25. v3 := int32(b2[3])
  26. v2 := int32(b2[2])
  27. v1 := int32(b2[1])
  28. v0 := int32(b2[0])
  29. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  30. }
  31. // Uint8 returns the next byte
  32. func (b *byteReader) Uint8() uint8 {
  33. v := b.b[b.off]
  34. return v
  35. }
  36. // Uint32 returns a little endian uint32 starting at current offset.
  37. func (b byteReader) Uint32() uint32 {
  38. if r := b.remain(); r < 4 {
  39. // Very rare
  40. v := uint32(0)
  41. for i := 1; i <= r; i++ {
  42. v = (v << 8) | uint32(b.b[len(b.b)-i])
  43. }
  44. return v
  45. }
  46. b2 := b.b[b.off:]
  47. b2 = b2[:4]
  48. v3 := uint32(b2[3])
  49. v2 := uint32(b2[2])
  50. v1 := uint32(b2[1])
  51. v0 := uint32(b2[0])
  52. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  53. }
  54. // Uint32NC returns a little endian uint32 starting at current offset.
  55. // The caller must be sure if there are at least 4 bytes left.
  56. func (b byteReader) Uint32NC() uint32 {
  57. b2 := b.b[b.off:]
  58. b2 = b2[:4]
  59. v3 := uint32(b2[3])
  60. v2 := uint32(b2[2])
  61. v1 := uint32(b2[1])
  62. v0 := uint32(b2[0])
  63. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  64. }
  65. // unread returns the unread portion of the input.
  66. func (b byteReader) unread() []byte {
  67. return b.b[b.off:]
  68. }
  69. // remain will return the number of bytes remaining.
  70. func (b byteReader) remain() int {
  71. return len(b.b) - b.off
  72. }