1 // Copyright 2011 The Go Authors. 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.
12 // bitReader wraps an io.Reader and provides the ability to read values,
13 // bit-by-bit, from it. Its Read* methods don't return the usual error
14 // because the error handling was verbose. Instead, any error is kept and can
15 // be checked afterwards.
16 type bitReader struct {
23 // newBitReader returns a new bitReader reading from r. If r is not
24 // already an io.ByteReader, it will be converted via a bufio.Reader.
25 func newBitReader(r io.Reader) bitReader {
26 byter, ok := r.(io.ByteReader)
28 byter = bufio.NewReader(r)
30 return bitReader{r: byter}
33 // ReadBits64 reads the given number of bits and returns them in the
34 // least-significant part of a uint64. In the event of an error, it returns 0
35 // and the error can be obtained by calling Err().
36 func (br *bitReader) ReadBits64(bits uint) (n uint64) {
38 b, err := br.r.ReadByte()
40 err = io.ErrUnexpectedEOF
51 // br.n looks like this (assuming that br.bits = 14 and bits = 6):
55 // (6 bits, the desired output)
61 // br.bits (num valid bits)
63 // This the next line right shifts the desired bits into the
64 // least-significant places and masks off anything above.
65 n = (br.n >> (br.bits - bits)) & ((1 << bits) - 1)
70 func (br *bitReader) ReadBits(bits uint) (n int) {
71 n64 := br.ReadBits64(bits)
75 func (br *bitReader) ReadBit() bool {
80 func (br *bitReader) Err() error {