Skip to content

Commit

Permalink
Duplicate slice passed to mongocrypt.newBinaryFromBytes().
Browse files Browse the repository at this point in the history
  • Loading branch information
qingyang-hu committed Aug 24, 2023
1 parent bbb9bc7 commit bcf5f70
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions x/mongo/driver/mongocrypt/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@

package mongocrypt

// #include <mongocrypt.h>
/*
#include <stdlib.h>
#include <mongocrypt.h>
*/
import "C"
import (
"unsafe"
)

// binary is a wrapper type around a mongocrypt_binary_t*
type binary struct {
p *C.uint8_t
wrapped *C.mongocrypt_binary_t
}

Expand All @@ -33,11 +37,11 @@ func newBinaryFromBytes(data []byte) *binary {
return newBinary()
}

// We don't need C.CBytes here because data cannot go out of scope. Any mongocrypt function that takes a
// mongocrypt_binary_t will make a copy of the data so the data can be garbage collected after calling.
addr := (*C.uint8_t)(unsafe.Pointer(&data[0])) // uint8_t*
dataLen := C.uint32_t(len(data)) // uint32_t
// TODO: Consider using runtime.Pinner to replace the C.CBytes after using go1.21.0.
addr := (*C.uint8_t)(C.CBytes(data)) // uint8_t*
dataLen := C.uint32_t(len(data)) // uint32_t
return &binary{
p: addr,
wrapped: C.mongocrypt_binary_new_from_data(addr, dataLen),
}
}
Expand All @@ -52,5 +56,8 @@ func (b *binary) toBytes() []byte {

// close cleans up any resources associated with the given binary instance.
func (b *binary) close() {
if b.p != nil {
C.free(unsafe.Pointer(b.p))
}
C.mongocrypt_binary_destroy(b.wrapped)
}

0 comments on commit bcf5f70

Please sign in to comment.