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 // bitReader needs to read bytes from an io.Reader. We attempt to cast the
24 // given io.Reader to this interface and, if it doesn't already fit, we wrap in
26 type byteReader interface {
27 ReadByte() (byte, error)
30 func newBitReader(r io.Reader) bitReader {
31 byter, ok := r.(byteReader)
33 byter = bufio.NewReader(r)
35 return bitReader{r: byter}
38 // ReadBits64 reads the given number of bits and returns them in the
39 // least-significant part of a uint64. In the event of an error, it returns 0
40 // and the error can be obtained by calling Err().
41 func (br *bitReader) ReadBits64(bits uint) (n uint64) {
43 b, err := br.r.ReadByte()
45 err = io.ErrUnexpectedEOF
56 // br.n looks like this (assuming that br.bits = 14 and bits = 6):
60 // (6 bits, the desired output)
66 // br.bits (num valid bits)
68 // This the next line right shifts the desired bits into the
69 // least-significant places and masks off anything above.
70 n = (br.n >> (br.bits - bits)) & ((1 << bits) - 1)
75 func (br *bitReader) ReadBits(bits uint) (n int) {
76 n64 := br.ReadBits64(bits)
80 func (br *bitReader) ReadBit() bool {
85 func (br *bitReader) Err() error {