Skip to content

cryptobyte: add uint48 methods #265

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cryptobyte/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ func (b *Builder) AddUint32(v uint32) {
b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}

// AddUint48 appends a big-endian, 48-bit value to the byte string.
func (b *Builder) AddUint48(v uint64) {
b.add(byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}

// AddUint64 appends a big-endian, 64-bit value to the byte string.
func (b *Builder) AddUint64(v uint64) {
b.add(byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
Expand Down
21 changes: 21 additions & 0 deletions cryptobyte/cryptobyte_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,27 @@ func TestUint32(t *testing.T) {
}
}

func TestUint48(t *testing.T) {
var b Builder
var u uint64 = 0xfefcff3cfdfc
b.AddUint48(u)
if err := builderBytesEq(&b, 254, 252, 255, 60, 253, 252); err != nil {
t.Error(err)
}

var s String = b.BytesOrPanic()
var v uint64
if !s.ReadUint48(&v) {
t.Error("ReadUint48() = false, want true")
}
if v != u {
t.Errorf("v = %x, want %x", v, u)
}
if len(s) != 0 {
t.Errorf("len(s) = %d, want 0", len(s))
}
}

func TestUint64(t *testing.T) {
var b Builder
b.AddUint64(0xf2fefefcff3cfdfc)
Expand Down
11 changes: 11 additions & 0 deletions cryptobyte/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ func (s *String) ReadUint32(out *uint32) bool {
return true
}

// ReadUint48 decodes a big-endian, 48-bit value into out and advances over it.
// It reports whether the read was successful.
func (s *String) ReadUint48(out *uint64) bool {
v := s.read(6)
if v == nil {
return false
}
*out = uint64(v[0])<<40 | uint64(v[1])<<32 | uint64(v[2])<<24 | uint64(v[3])<<16 | uint64(v[4])<<8 | uint64(v[5])
return true
}

// ReadUint64 decodes a big-endian, 64-bit value into out and advances over it.
// It reports whether the read was successful.
func (s *String) ReadUint64(out *uint64) bool {
Expand Down