bytereader.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. // init will initialize the reader and set the input.
  14. func (b *byteReader) init(in []byte) {
  15. b.b = in
  16. b.off = 0
  17. }
  18. // advance the stream b n bytes.
  19. func (b *byteReader) advance(n uint) {
  20. b.off += int(n)
  21. }
  22. // overread returns whether we have advanced too far.
  23. func (b *byteReader) overread() bool {
  24. return b.off > len(b.b)
  25. }
  26. // Int32 returns a little endian int32 starting at current offset.
  27. func (b byteReader) Int32() int32 {
  28. b2 := b.b[b.off:]
  29. b2 = b2[:4]
  30. v3 := int32(b2[3])
  31. v2 := int32(b2[2])
  32. v1 := int32(b2[1])
  33. v0 := int32(b2[0])
  34. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  35. }
  36. // Uint8 returns the next byte
  37. func (b *byteReader) Uint8() uint8 {
  38. v := b.b[b.off]
  39. return v
  40. }
  41. // Uint32 returns a little endian uint32 starting at current offset.
  42. func (b byteReader) Uint32() uint32 {
  43. if r := b.remain(); r < 4 {
  44. // Very rare
  45. v := uint32(0)
  46. for i := 1; i <= r; i++ {
  47. v = (v << 8) | uint32(b.b[len(b.b)-i])
  48. }
  49. return v
  50. }
  51. b2 := b.b[b.off:]
  52. b2 = b2[:4]
  53. v3 := uint32(b2[3])
  54. v2 := uint32(b2[2])
  55. v1 := uint32(b2[1])
  56. v0 := uint32(b2[0])
  57. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  58. }
  59. // Uint32NC returns a little endian uint32 starting at current offset.
  60. // The caller must be sure if there are at least 4 bytes left.
  61. func (b byteReader) Uint32NC() uint32 {
  62. b2 := b.b[b.off:]
  63. b2 = b2[:4]
  64. v3 := uint32(b2[3])
  65. v2 := uint32(b2[2])
  66. v1 := uint32(b2[1])
  67. v0 := uint32(b2[0])
  68. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  69. }
  70. // unread returns the unread portion of the input.
  71. func (b byteReader) unread() []byte {
  72. return b.b[b.off:]
  73. }
  74. // remain will return the number of bytes remaining.
  75. func (b byteReader) remain() int {
  76. return len(b.b) - b.off
  77. }