bytereader.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 : b.off+4 : b.off+4]
  29. v3 := int32(b2[3])
  30. v2 := int32(b2[2])
  31. v1 := int32(b2[1])
  32. v0 := int32(b2[0])
  33. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  34. }
  35. // Uint8 returns the next byte
  36. func (b *byteReader) Uint8() uint8 {
  37. v := b.b[b.off]
  38. return v
  39. }
  40. // Uint32 returns a little endian uint32 starting at current offset.
  41. func (b byteReader) Uint32() uint32 {
  42. if r := b.remain(); r < 4 {
  43. // Very rare
  44. v := uint32(0)
  45. for i := 1; i <= r; i++ {
  46. v = (v << 8) | uint32(b.b[len(b.b)-i])
  47. }
  48. return v
  49. }
  50. b2 := b.b[b.off : b.off+4 : b.off+4]
  51. v3 := uint32(b2[3])
  52. v2 := uint32(b2[2])
  53. v1 := uint32(b2[1])
  54. v0 := uint32(b2[0])
  55. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  56. }
  57. // unread returns the unread portion of the input.
  58. func (b byteReader) unread() []byte {
  59. return b.b[b.off:]
  60. }
  61. // remain will return the number of bytes remaining.
  62. func (b byteReader) remain() int {
  63. return len(b.b) - b.off
  64. }