Skip to content

GODRIVER-2311 Improve the BSON unmarshal buffer reuse fix to reduce memory allocations. #891

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

Merged
merged 1 commit into from
Mar 31, 2022
Merged
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
14 changes: 9 additions & 5 deletions bson/bsonrw/value_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,9 +384,13 @@ func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) {
if err != nil {
return nil, 0, err
}
// Make a copy of the returned byte slice because it's just a subslice from the valueReader's
// buffer and is not safe to return in the unmarshaled value.
cp := make([]byte, len(b))
copy(cp, b)

vr.pop()
return b, btype, nil
return cp, btype, nil
}

func (vr *valueReader) ReadBoolean() (bool, error) {
Expand Down Expand Up @@ -737,6 +741,9 @@ func (vr *valueReader) ReadValue() (ValueReader, error) {
return vr, nil
}

// readBytes reads length bytes from the valueReader starting at the current offset. Note that the
// returned byte slice is a subslice from the valueReader buffer and must be converted or copied
// before returning in an unmarshaled value.
func (vr *valueReader) readBytes(length int32) ([]byte, error) {
if length < 0 {
return nil, fmt.Errorf("invalid length: %d", length)
Expand All @@ -749,10 +756,7 @@ func (vr *valueReader) readBytes(length int32) ([]byte, error) {
start := vr.offset
vr.offset += int64(length)

b := make([]byte, length)
copy(b, vr.d[start:start+int64(length)])

return b, nil
return vr.d[start : start+int64(length)], nil
}

func (vr *valueReader) appendBytes(dst []byte, length int32) ([]byte, error) {
Expand Down