Skip to content

Commit

Permalink
nazabits: new func ReadString, ReadBits32IgnErr, ReadStringIgnErr
Browse files Browse the repository at this point in the history
  • Loading branch information
q191201771 committed Jun 17, 2024
1 parent 5d45d1d commit 2a2e292
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
25 changes: 23 additions & 2 deletions pkg/nazabits/bits.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import "errors"

var ErrNazaBits = errors.New("nazabits: fxxk")

// 按位流式读取字节切片
// BitReader 按位流式读取字节切片
// 从高位向低位读
// 注意,可以在每次读取后,判断是否发生错误。也可以在多次读取后,判断是否发生错误。
type BitReader struct {
core []byte
avail uint // 还没有读取的bit数量
index uint // 从0开始
index uint // 从0开始,待读取的字节下标
pos uint // 从左往右,从高位往低位 [0, 7]
err error
}
Expand Down Expand Up @@ -131,6 +131,7 @@ func (br *BitReader) ReadBits64(n uint) (r uint64, err error) {
}
}

// ReadBytes
// @param n: 读取多少个字节
func (br *BitReader) ReadBytes(n uint) (r []byte, err error) {
// 对常见的pos为0的情况单独做优化
Expand All @@ -155,6 +156,16 @@ func (br *BitReader) ReadBytes(n uint) (r []byte, err error) {
return
}

func (br *BitReader) ReadString(n uint) (r string, err error) {
var bs []byte
bs, err = br.ReadBytes(n)
if err != nil {
return
}
r = string(bs)
return
}

func (br *BitReader) ReadGolomb() (v uint32, err error) {
return br.ReadUeGolomb()
}
Expand Down Expand Up @@ -196,6 +207,16 @@ func (br *BitReader) ReadSeGolomb() (v int32, err error) {
return
}

func (br *BitReader) ReadBits32IgnErr(n uint) uint32 {
r, _ := br.ReadBits32(n)
return r
}

func (br *BitReader) ReadStringIgnErr(n uint) string {
r, _ := br.ReadString(n)
return r
}

func (br *BitReader) SkipBytes(n uint) error {
if err := br.reserve(n * 8); err != nil {
return err
Expand Down
18 changes: 18 additions & 0 deletions pkg/nazabits/bits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,24 @@ func TestBitReader_ReadBytes(t *testing.T) {
}
}

func TestBitReader_ReadString(t *testing.T) {
v := []byte{48, 57, 49, 56}
{
br := nazabits.NewBitReader(v)
r, err := br.ReadString(2)
assert.Equal(t, nil, err)
assert.Equal(t, "09", r)
assert.Equal(t, nil, br.Err())

r = br.ReadStringIgnErr(2)
assert.Equal(t, "18", r)

br.ReadStringIgnErr(1)
assert.Equal(t, nazabits.ErrNazaBits, br.Err())

}
}

func TestBitReader_ReadGolomb(t *testing.T) {
var b []byte
var v uint32
Expand Down

0 comments on commit 2a2e292

Please sign in to comment.