Source File
bit_reader.go
Belonging Package
compress/bzip2
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bzip2
import (
)
// bitReader wraps an io.Reader and provides the ability to read values,
// bit-by-bit, from it. Its Read* methods don't return the usual error
// because the error handling was verbose. Instead, any error is kept and can
// be checked afterwards.
type bitReader struct {
r io.ByteReader
n uint64
bits uint
err error
}
// newBitReader returns a new bitReader reading from r. If r is not
// already an io.ByteReader, it will be converted via a bufio.Reader.
func newBitReader( io.Reader) bitReader {
, := .(io.ByteReader)
if ! {
= bufio.NewReader()
}
return bitReader{r: }
}
// ReadBits64 reads the given number of bits and returns them in the
// least-significant part of a uint64. In the event of an error, it returns 0
// and the error can be obtained by calling bitReader.Err().
func ( *bitReader) ( uint) ( uint64) {
for > .bits {
, := .r.ReadByte()
if == io.EOF {
= io.ErrUnexpectedEOF
}
if != nil {
.err =
return 0
}
.n <<= 8
.n |= uint64()
.bits += 8
}
// br.n looks like this (assuming that br.bits = 14 and bits = 6):
// Bit: 111111
// 5432109876543210
//
// (6 bits, the desired output)
// |-----|
// V V
// 0101101101001110
// ^ ^
// |------------|
// br.bits (num valid bits)
//
// The next line right shifts the desired bits into the
// least-significant places and masks off anything above.
= (.n >> (.bits - )) & ((1 << ) - 1)
.bits -=
return
}
func ( *bitReader) ( uint) ( int) {
:= .ReadBits64()
return int()
}
func ( *bitReader) () bool {
:= .ReadBits(1)
return != 0
}
func ( *bitReader) () error {
return .err
}
The pages are generated with Golds v0.7.0-preview. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |