2019-10-25 15:06:47 -04:00
|
|
|
package Common
|
|
|
|
|
|
|
|
import "log"
|
|
|
|
|
|
|
|
// BitStream is a utility class for reading groups of bits from a stream
|
|
|
|
type BitStream struct {
|
|
|
|
data []byte
|
|
|
|
dataPosition int
|
|
|
|
current int
|
|
|
|
bitCount int
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:09:07 -04:00
|
|
|
// CreateBitStream creates a new BitStream
|
2019-10-25 15:06:47 -04:00
|
|
|
func CreateBitStream(newData []byte) *BitStream {
|
|
|
|
result := &BitStream{
|
|
|
|
data: newData,
|
|
|
|
dataPosition: 0,
|
|
|
|
current: 0,
|
|
|
|
bitCount: 0,
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:09:07 -04:00
|
|
|
// ReadBits reads the specified number of bits and returns the value
|
2019-10-25 15:06:47 -04:00
|
|
|
func (v *BitStream) ReadBits(bitCount int) int {
|
|
|
|
if bitCount > 16 {
|
|
|
|
log.Panic("Maximum BitCount is 16")
|
|
|
|
}
|
|
|
|
if !v.EnsureBits(bitCount) {
|
|
|
|
return -1
|
|
|
|
}
|
2019-11-01 03:36:29 -04:00
|
|
|
result := v.current & (0xffff >> uint(16-bitCount))
|
2019-10-25 15:06:47 -04:00
|
|
|
v.WasteBits(bitCount)
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:09:07 -04:00
|
|
|
// PeekByte returns the current byte without adjusting the position
|
2019-10-25 15:06:47 -04:00
|
|
|
func (v *BitStream) PeekByte() int {
|
|
|
|
if !v.EnsureBits(8) {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return v.current & 0xff
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:09:07 -04:00
|
|
|
// EnsureBits ensures that the specified number of bits are available
|
2019-10-25 15:06:47 -04:00
|
|
|
func (v *BitStream) EnsureBits(bitCount int) bool {
|
|
|
|
if bitCount <= v.bitCount {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if v.dataPosition >= len(v.data) {
|
|
|
|
return false
|
|
|
|
}
|
2019-10-26 20:09:33 -04:00
|
|
|
nextValue := v.data[v.dataPosition]
|
2019-10-25 15:06:47 -04:00
|
|
|
v.dataPosition++
|
2019-11-01 03:36:29 -04:00
|
|
|
v.current |= int(nextValue) << uint(v.bitCount)
|
2019-10-25 15:06:47 -04:00
|
|
|
v.bitCount += 8
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:09:07 -04:00
|
|
|
// WasteBits dry-reads the specified number of bits
|
2019-10-25 15:06:47 -04:00
|
|
|
func (v *BitStream) WasteBits(bitCount int) {
|
2019-11-01 03:36:29 -04:00
|
|
|
v.current >>= uint(bitCount)
|
2019-10-25 15:06:47 -04:00
|
|
|
v.bitCount -= bitCount
|
|
|
|
}
|