Skip to content

Commit

Permalink
Merge pull request #335 from ldclabs/master
Browse files Browse the repository at this point in the history
Reuse underlying array if RawMessage has sufficient capacity
  • Loading branch information
fxamacker authored May 9, 2022
2 parents 89cef41 + e661c65 commit 7be1c8e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
3 changes: 1 addition & 2 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ func (m *RawMessage) UnmarshalCBOR(data []byte) error {
if m == nil {
return errors.New("cbor.RawMessage: UnmarshalCBOR on nil pointer")
}
*m = make([]byte, len(data))
copy(*m, data)
*m = append((*m)[0:0], data...)
return nil
}
15 changes: 15 additions & 0 deletions stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package cbor

import (
"bytes"
"fmt"
"io"
"reflect"
"testing"
Expand Down Expand Up @@ -387,6 +388,20 @@ func TestRawMessage(t *testing.T) {
if !bytes.Equal(b, cborData) {
t.Errorf("Marshal(%+v) = 0x%x, want 0x%x", v, b, cborData)
}

address := fmt.Sprintf("%p", *v.B)
if err := Unmarshal(v.A, v.B); err != nil {
t.Fatalf("Unmarshal(0x%x) returned error %v", v.A, err)
}
if address != fmt.Sprintf("%p", *v.B) {
t.Fatalf("Unmarshal RawMessage should reuse underlying array if it has sufficient capacity")
}
if err := Unmarshal(cborData, v.B); err != nil {
t.Fatalf("Unmarshal(0x%x) returned error %v", cborData, err)
}
if address == fmt.Sprintf("%p", *v.B) {
t.Fatalf("Unmarshal RawMessage should allocate a new underlying array if it does not have sufficient capacity")
}
}

func TestNullRawMessage(t *testing.T) {
Expand Down

0 comments on commit 7be1c8e

Please sign in to comment.