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

Reuse underlying array if RawMessage has sufficient capacity #335

Merged
merged 1 commit into from
May 9, 2022
Merged
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
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