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