Skip to content

Commit

Permalink
length func for varint length (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
tigh-latte committed Dec 14, 2021
1 parent e5bae46 commit 18b76ae
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions varint.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ func NewVarIntFromBytes(bb []byte) (VarInt, int) {
}
}

// Length return the length of the underlying byte representation of the `bt.VarInt`.
func (v VarInt) Length() int {
if v < 253 {
return 1
}
if v < 65536 {
return 3
}
if v < 4294967296 {
return 5
}
return 9
}

// Bytes takes the underlying unsigned integer and returns a byte array in VarInt format.
// See http://learnmeabitcoin.com/glossary/varint
func (v VarInt) Bytes() []byte {
Expand Down
38 changes: 38 additions & 0 deletions varint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,41 @@ func TestVarInt(t *testing.T) {
})
}
}

func TestVarInt_Size(t *testing.T) {
tests := map[string]struct {
v bt.VarInt
expSize int
}{
"252 returns 1": {
v: bt.VarInt(252),
expSize: 1,
},
"253 returns 3": {
v: bt.VarInt(253),
expSize: 3,
},
"65535 returns 3": {
v: bt.VarInt(65535),
expSize: 3,
},
"65536 returns 5": {
v: bt.VarInt(65536),
expSize: 5,
},
"4294967295 returns 5": {
v: bt.VarInt(4294967295),
expSize: 5,
},
"4294967296 returns 9": {
v: bt.VarInt(4294967296),
expSize: 9,
},
}

for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, test.expSize, test.v.Length())
})
}
}

0 comments on commit 18b76ae

Please sign in to comment.