bytereader.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2018 Klaus Post. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Based on work Copyright (c) 2013, Yann Collet, released under BSD License.
  5. package fse
  6. // byteReader provides a byte reader that reads
  7. // little endian values from a byte stream.
  8. // The input stream is manually advanced.
  9. // The reader performs no bounds checks.
  10. type byteReader struct {
  11. b []byte
  12. off int
  13. }
  14. // init will initialize the reader and set the input.
  15. func (b *byteReader) init(in []byte) {
  16. b.b = in
  17. b.off = 0
  18. }
  19. // advance the stream b n bytes.
  20. func (b *byteReader) advance(n uint) {
  21. b.off += int(n)
  22. }
  23. // Int32 returns a little endian int32 starting at current offset.
  24. func (b byteReader) Int32() int32 {
  25. b2 := b.b[b.off : b.off+4 : b.off+4]
  26. v3 := int32(b2[3])
  27. v2 := int32(b2[2])
  28. v1 := int32(b2[1])
  29. v0 := int32(b2[0])
  30. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  31. }
  32. // Uint32 returns a little endian uint32 starting at current offset.
  33. func (b byteReader) Uint32() uint32 {
  34. b2 := b.b[b.off : b.off+4 : b.off+4]
  35. v3 := uint32(b2[3])
  36. v2 := uint32(b2[2])
  37. v1 := uint32(b2[1])
  38. v0 := uint32(b2[0])
  39. return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
  40. }
  41. // unread returns the unread portion of the input.
  42. func (b byteReader) unread() []byte {
  43. return b.b[b.off:]
  44. }
  45. // remain will return the number of bytes remaining.
  46. func (b byteReader) remain() int {
  47. return len(b.b) - b.off
  48. }