Skip to content

Commit

Permalink
Implment NData()
Browse files Browse the repository at this point in the history
  • Loading branch information
lestrrat committed Nov 17, 2015
1 parent 91ec2c1 commit d1e3756
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions buffer/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func FromUint(v uint64) Buffer {
return Buffer(data[i:])
}

// FromBase64 constructs a new Buffer from a base64 encoded data
func FromBase64(v []byte) (Buffer, error) {
b := Buffer{}
if err := b.Base64Decode(v); err != nil {
Expand All @@ -38,11 +39,31 @@ func FromBase64(v []byte) (Buffer, error) {
return b, nil
}

// FromNData constructs a new Buffer from a "n:data" format
// (I made that name up)
func FromNData(v []byte) (Buffer, error) {
size := binary.BigEndian.Uint32(v)
buf := make([]byte, int(size))
copy(buf, v[4:4+size])
return Buffer(buf), nil
}

// Bytes returns the raw bytes that comprises the Buffer
func (b Buffer) Bytes() []byte {
return []byte(b)
}

// NData returns Datalen || Data, where Datalen is a 32 bit counter for
// the length of the following data, and Data is the octets that comprise
// the buffer data
func (b Buffer) NData() []byte {
buf := make([]byte, 4+b.Len())
binary.BigEndian.PutUint32(buf, uint32(b.Len()))

copy(buf[4:], b.Bytes())
return buf
}

// Len returns the number of bytes that the Buffer holds
func (b Buffer) Len() int {
return len(b)
Expand Down
17 changes: 17 additions & 0 deletions buffer/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,21 @@ func TestFunky(t *testing.T) {
if !assert.Equal(t, 257, b.Len(), "Should 257 bytes") {
return
}
}

func TestBuffer_NData(t *testing.T) {
payload := []byte("Alice")
nd := Buffer(payload).NData()
if !assert.Equal(t, []byte{0,0,0,5,65,108,105,99,101}, nd, "NData mathces") {
return
}

b1, err := FromNData(nd)
if !assert.NoError(t, err, "FromNData succeeds") {
return
}

if !assert.Equal(t, payload, b1.Bytes(), "payload matches") {
return
}
}

0 comments on commit d1e3756

Please sign in to comment.