Skip to content

Commit

Permalink
feat: add Bytes func to AttributeDecoder
Browse files Browse the repository at this point in the history
For symmetry with AttributeEncoder, adds a Bytes function to
AttriuteDecoder that copies the bytes to a new slice to avoid retaining
the original.

Bug: mdlayher#103
  • Loading branch information
terinjokes committed Sep 7, 2018
1 parent 1aa84f5 commit 87f1a73
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,14 @@ func (ad *AttributeDecoder) Err() error {
return ad.err
}

// Bytes returns the raw bytes of the current Attribute's data.
func (ad *AttributeDecoder) Bytes() []byte {
src := ad.data()
dest := make([]byte, len(src))
copy(dest, src)
return dest
}

// String returns the string representation of the current Attribute's data.
func (ad *AttributeDecoder) String() string {
if ad.err != nil {
Expand Down
26 changes: 26 additions & 0 deletions attribute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,32 @@ func TestAttributeDecoderOK(t *testing.T) {
attrs: adEndianAttrs(binary.BigEndian),
fn: adEndianTest(binary.BigEndian),
},
{
name: "bytes",
attrs: []Attribute{{
Type: 1,
Data: []byte{0xde, 0xad},
}},
fn: func(ad *AttributeDecoder) {
var b []byte
switch t := ad.Type(); t {
case 1:
b = ad.Bytes()
default:
panicf("unhandled attribute type: %d", t)
}

if diff := cmp.Diff([]byte{0xde, 0xad}, b); diff != "" {
panicf("unexpected attribute value (-want +got):\n%s", diff)
}

b[0] = 0xff

if diff := cmp.Diff(b, ad.Bytes()); diff == "" {
panic("expected attribute value to be copied and different")
}
},
},
{
name: "string",
attrs: []Attribute{{
Expand Down

0 comments on commit 87f1a73

Please sign in to comment.