1
1
mirror of https://github.com/OpenDiablo2/OpenDiablo2 synced 2024-11-17 01:51:14 -05:00
OpenDiablo2/d2common/bitstream.go

65 lines
1.4 KiB
Go
Raw Normal View History

2019-11-10 03:36:53 -05:00
package d2common
2019-10-25 15:06:47 -04:00
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
}
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++
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) {
v.current >>= uint(bitCount)
2019-10-25 15:06:47 -04:00
v.bitCount -= bitCount
}