Skip to content
This repository has been archived by the owner on Dec 20, 2021. It is now read-only.

bitmuncher: add missing methods from stream reader #1123

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
21 changes: 21 additions & 0 deletions d2common/d2datautils/bitmuncher.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const (
byteLen = 8
oneBit = 0x01
fourBytes = byteLen * 4
twoBytes = byteLen * 2
)

// CreateBitMuncher Creates a BitMuncher
Expand Down Expand Up @@ -79,6 +80,16 @@ func (v *BitMuncher) GetByte() byte {
return byte(v.GetBits(byteLen))
}

// GetInt16 reads an int16 from data
func (v *BitMuncher) GetInt16() int16 {
return int16(v.MakeSigned(v.GetBits(twoBytes), twoBytes))
}

// GetUInt16 reads an unsigned uint16 from data
func (v *BitMuncher) GetUInt16() uint16 {
return uint16(v.GetBits(twoBytes))
}

// GetInt32 reads an int32 from data
func (v *BitMuncher) GetInt32() int32 {
return v.MakeSigned(v.GetBits(fourBytes), fourBytes)
Expand All @@ -104,6 +115,16 @@ func (v *BitMuncher) GetBits(bits int) uint32 {
return result
}

// GetBytes returns byte slice of `n` length.
func (v *BitMuncher) GetBytes(n int) (result []byte) {
result = make([]byte, n)
for i := 0; i < n; i++ {
result[i] = v.GetByte()
}

return result
}

// GetSignedBits Given a number of bits, reads that many bits and returns as int
func (v *BitMuncher) GetSignedBits(bits int) int {
return int(v.MakeSigned(v.GetBits(bits), bits))
Expand Down
30 changes: 30 additions & 0 deletions d2common/d2datautils/bitmuncher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ func TestBitmuncherGetBits(t *testing.T) {
assert.Equal(t, byte(bm.GetBits(bitsPerByte)), testData[0], "get bits didn't return expected value")
}

func TestBitmuncherGetBytes(t *testing.T) {
bm := CreateBitMuncher(testData, 0)

assert.Equal(t, bm.GetBytes(4), testData[0:4], "get bytes didn't return expected value")
}

func TestBitmuncherGetNoBits(t *testing.T) {
bm := CreateBitMuncher(testData, 0)

Expand Down Expand Up @@ -82,6 +88,30 @@ func TestBitmuncherSkipBits(t *testing.T) {
assert.Equal(t, bm.GetByte(), testData[1], "skipping 8 bits didn't moved bit muncher's position into next byte")
}

func TestBitmuncherGetInt16(t *testing.T) {
bm := CreateBitMuncher(testData, 0)

var testInt int16

for i := 0; i < bytesPerint16; i++ {
testInt |= int16(testData[i]) << int16(bitsPerByte*i)
}

assert.Equal(t, bm.GetInt16(), testInt, "int16 value wasn't returned properly")
}

func TestBitmuncherGetUint16(t *testing.T) {
bm := CreateBitMuncher(testData, 0)

var testUint uint16

for i := 0; i < bytesPerint16; i++ {
testUint |= uint16(testData[i]) << uint16(bitsPerByte*i)
}

assert.Equal(t, bm.GetUInt16(), testUint, "uint16 value wasn't returned properly")
}

func TestBitmuncherGetInt32(t *testing.T) {
bm := CreateBitMuncher(testData, 0)

Expand Down