blob: dc4378b64012866143716c3bd982c38894111c32 [file] [log] [blame]
Scott Bakered4efab2020-01-13 19:12:25 -08001// 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
5package zstd
6
7// byteReader provides a byte reader that reads
8// little endian values from a byte stream.
9// The input stream is manually advanced.
10// The reader performs no bounds checks.
11type byteReader struct {
12 b []byte
13 off int
14}
15
16// init will initialize the reader and set the input.
17func (b *byteReader) init(in []byte) {
18 b.b = in
19 b.off = 0
20}
21
22// advance the stream b n bytes.
23func (b *byteReader) advance(n uint) {
24 b.off += int(n)
25}
26
27// overread returns whether we have advanced too far.
28func (b *byteReader) overread() bool {
29 return b.off > len(b.b)
30}
31
32// Int32 returns a little endian int32 starting at current offset.
33func (b byteReader) Int32() int32 {
34 b2 := b.b[b.off : b.off+4 : b.off+4]
35 v3 := int32(b2[3])
36 v2 := int32(b2[2])
37 v1 := int32(b2[1])
38 v0 := int32(b2[0])
39 return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
40}
41
42// Uint8 returns the next byte
43func (b *byteReader) Uint8() uint8 {
44 v := b.b[b.off]
45 return v
46}
47
48// Uint32 returns a little endian uint32 starting at current offset.
49func (b byteReader) Uint32() uint32 {
50 if r := b.remain(); r < 4 {
51 // Very rare
52 v := uint32(0)
53 for i := 1; i <= r; i++ {
54 v = (v << 8) | uint32(b.b[len(b.b)-i])
55 }
56 return v
57 }
58 b2 := b.b[b.off : b.off+4 : b.off+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
66// unread returns the unread portion of the input.
67func (b byteReader) unread() []byte {
68 return b.b[b.off:]
69}
70
71// remain will return the number of bytes remaining.
72func (b byteReader) remain() int {
73 return len(b.b) - b.off
74}