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

fix: allocate new slices for component nodes #57

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
37 changes: 25 additions & 12 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ func DecodeBytes(na ipld.NodeAssembler, src []byte) error {
return fmt.Errorf("protobuf: (PBNode) duplicate Data section")
}

chunk, n := protowire.ConsumeBytes(remaining)
if n < 0 {
return protowire.ParseError(n)
chunk, n, err := consumeBytes(remaining, true)
if err != nil {
return err
}
remaining = remaining[n:]

Expand All @@ -97,9 +97,9 @@ func DecodeBytes(na ipld.NodeAssembler, src []byte) error {
haveData = true

case 2:
chunk, n := protowire.ConsumeBytes(remaining)
if n < 0 {
return protowire.ParseError(n)
chunk, n, err := consumeBytes(remaining, false) // no need to alloc here, unmarshalLink will do that
if err != nil {
return err
}
remaining = remaining[n:]

Expand Down Expand Up @@ -188,9 +188,9 @@ func unmarshalLink(remaining []byte, ma ipld.MapAssembler) error {
return fmt.Errorf("protobuf: (PBLink) wrong wireType (%d) for Hash", wireType)
}

chunk, n := protowire.ConsumeBytes(remaining)
if n < 0 {
return protowire.ParseError(n)
chunk, n, err := consumeBytes(remaining, true)
if err != nil {
return err
}
remaining = remaining[n:]

Expand All @@ -217,9 +217,9 @@ func unmarshalLink(remaining []byte, ma ipld.MapAssembler) error {
return fmt.Errorf("protobuf: (PBLink) wrong wireType (%d) for Name", wireType)
}

chunk, n := protowire.ConsumeBytes(remaining)
if n < 0 {
return protowire.ParseError(n)
chunk, n, err := consumeBytes(remaining, true)
if err != nil {
return err
}
remaining = remaining[n:]

Expand Down Expand Up @@ -264,3 +264,16 @@ func unmarshalLink(remaining []byte, ma ipld.MapAssembler) error {

return nil
}

// consumeBytes will read a Bytes section from the begining of the provided slice, return it and the number
// of bytes consumed in the process and optionally return it as a newly allocated slice
func consumeBytes(byts []byte, alloc bool) ([]byte, int, error) {
chunk, n := protowire.ConsumeBytes(byts)
if n < 0 {
return nil, 0, protowire.ParseError(n)
}
if alloc {
return append(make([]byte, 0, len(chunk)), chunk...), n, nil
}
return chunk, n, nil
}