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.
14
// bitReader reads a bitstream in reverse.
15
// The last set bit indicates the start of the stream and is used
16
// for aligning the input.
17
type bitReader struct {
19
off uint // next byte to read is at in[off - 1]
24
// init initializes and resets the bit reader.
25
func (b *bitReader) init(in []byte) error {
27
return errors.New("corrupt stream: too short")
31
// The highest bit of the last byte indicates where to start
34
return errors.New("corrupt stream, did not find end of stream")
44
b.bitsRead += 8 - uint8(highBits(uint32(v)))
48
// getBits will return n bits. n can be 0.
49
func (b *bitReader) getBits(n uint8) uint16 {
50
if n == 0 || b.bitsRead >= 64 {
53
return b.getBitsFast(n)
56
// getBitsFast requires that at least one bit is requested every time.
57
// There are no checks if the buffer is filled.
58
func (b *bitReader) getBitsFast(n uint8) uint16 {
59
const regMask = 64 - 1
60
v := uint16((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask))
65
// fillFast() will make sure at least 32 bits are available.
66
// There must be at least 4 bytes available.
67
func (b *bitReader) fillFast() {
74
low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24)
75
b.value = (b.value << 32) | uint64(low)
80
// fill() will make sure at least 32 bits are available.
81
func (b *bitReader) fill() {
88
low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24)
89
b.value = (b.value << 32) | uint64(low)
95
b.value = (b.value << 8) | uint64(b.in[b.off-1])
101
// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read.
102
func (b *bitReader) fillFastStart() {
103
// Do single re-slice to avoid bounds checks.
104
b.value = binary.LittleEndian.Uint64(b.in[b.off-8:])
109
// finished returns true if all bits have been read from the bit stream.
110
func (b *bitReader) finished() bool {
111
return b.bitsRead >= 64 && b.off == 0
114
// close the bitstream and returns an error if out-of-buffer reads occurred.
115
func (b *bitReader) close() error {
116
// Release reference.
119
return io.ErrUnexpectedEOF