Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
qingyang-hu committed Dec 6, 2023
1 parent cf50fcb commit 40c94dd
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions bson/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,22 +73,32 @@ func MarshalValue(val interface{}) (bsontype.Type, []byte, error) {
return MarshalValueWithRegistry(DefaultRegistry, val)
}

// MarshalValueAppend will append the BSON encoding of val to dst. If dst is not large enough to hold the BSON encoding
// of val, dst will be grown.
//
// Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go
// Driver 2.0.
func MarshalValueAppend(dst []byte, val interface{}) (bsontype.Type, []byte, error) {
return MarshalValueAppendWithRegistry(DefaultRegistry, dst, val)
}

// MarshalValueWithRegistry returns the BSON encoding of val using Registry r.
//
// Deprecated: Using a custom registry to marshal individual BSON values will not be supported in Go
// Driver 2.0.
func MarshalValueWithRegistry(r *bsoncodec.Registry, val interface{}) (bsontype.Type, []byte, error) {
dst := make([]byte, 0)
return MarshalValueAppendWithRegistry(r, dst, val)
sw := new(bsonrw.SliceWriter)
*sw = make([]byte, 0)
vwFlusher := bvwPool.GetAtModeElement(sw)

// get an Encoder and encode the value
enc := encPool.Get().(*Encoder)
defer encPool.Put(enc)
enc.Reset(vwFlusher)
enc.ec = bsoncodec.EncodeContext{Registry: r}
if err := enc.Encode(val); err != nil {
return 0, nil, err
}

// flush the bytes written because we cannot guarantee that a full document has been written
// after the flush, *sw will be in the format
// [value type, 0 (null byte to indicate end of empty element name), value bytes..]
if err := vwFlusher.Flush(); err != nil {
return 0, nil, err
}
buffer := *sw
return bsontype.Type(buffer[0]), buffer[2:], nil
}

// MarshalValueWithContext returns the BSON encoding of val using EncodeContext ec.
Expand Down

0 comments on commit 40c94dd

Please sign in to comment.