Skip to content
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

x/crypto: add ReadUint32LengthPrefixed #196

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 21 additions & 0 deletions cryptobyte/cryptobyte_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,27 @@ func TestUint8LengthPrefixedNested(t *testing.T) {
}
}

func TestUint32LengthPrefixedSimple(t *testing.T) {
var b Builder
b.AddUint32LengthPrefixed(func(c *Builder) {
c.AddUint8(23)
c.AddUint8(42)
})
if err := builderBytesEq(&b, 0, 0, 0, 2, 23, 42); err != nil {
t.Error(err)
}
var s, out String = String(b.BytesOrPanic()), nil
if !s.ReadUint32LengthPrefixed(&out) {
t.Error("read failed")
}
if len(out) != 2 || out[0] != 23 || out[1] != 42 {
t.Error("read incorrect value")
}
if len(s) != 0 {
t.Error("incorrect source length")
}
}

func TestPreallocatedBuffer(t *testing.T) {
var buf [5]byte
b := NewBuilder(buf[0:0])
Expand Down
11 changes: 10 additions & 1 deletion cryptobyte/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool {
length = length << 8
length = length | uint32(b)
}
v := s.read(int(length))
n := int(length)
v := s.read(n) // returns nil if n is negative due to overflow
if v == nil {
return false
}
Expand Down Expand Up @@ -133,6 +134,14 @@ func (s *String) ReadUint24LengthPrefixed(out *String) bool {
return s.readLengthPrefixed(3, out)
}

// ReadUint32LengthPrefixed reads the content of a big-endian, 32-bit
// length-prefixed value into out and advances over it. It reports whether
// the read was successful.
// On 32-bit platform read fails if length is greater than max int.
func (s *String) ReadUint32LengthPrefixed(out *String) bool {
return s.readLengthPrefixed(4, out)
}

// ReadBytes reads n bytes into out and advances over them. It reports
// whether the read was successful.
func (s *String) ReadBytes(out *[]byte, n int) bool {
Expand Down