github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/binary.go (about)

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  //go:build cse
     8  // +build cse
     9  
    10  package mongocrypt
    11  
    12  // #include <mongocrypt.h>
    13  import "C"
    14  import (
    15  	"unsafe"
    16  )
    17  
    18  // binary is a wrapper type around a mongocrypt_binary_t*
    19  type binary struct {
    20  	wrapped *C.mongocrypt_binary_t
    21  }
    22  
    23  // newBinary creates an empty binary instance.
    24  func newBinary() *binary {
    25  	return &binary{
    26  		wrapped: C.mongocrypt_binary_new(),
    27  	}
    28  }
    29  
    30  // newBinaryFromBytes creates a binary instance from a byte buffer.
    31  func newBinaryFromBytes(data []byte) *binary {
    32  	if len(data) == 0 {
    33  		return newBinary()
    34  	}
    35  
    36  	// We don't need C.CBytes here because data cannot go out of scope. Any mongocrypt function that takes a
    37  	// mongocrypt_binary_t will make a copy of the data so the data can be garbage collected after calling.
    38  	addr := (*C.uint8_t)(unsafe.Pointer(&data[0])) // uint8_t*
    39  	dataLen := C.uint32_t(len(data))               // uint32_t
    40  	return &binary{
    41  		wrapped: C.mongocrypt_binary_new_from_data(addr, dataLen),
    42  	}
    43  }
    44  
    45  // toBytes converts the given binary instance to []byte.
    46  func (b *binary) toBytes() []byte {
    47  	dataPtr := C.mongocrypt_binary_data(b.wrapped) // C.uint8_t*
    48  	dataLen := C.mongocrypt_binary_len(b.wrapped)  // C.uint32_t
    49  
    50  	return C.GoBytes(unsafe.Pointer(dataPtr), C.int(dataLen))
    51  }
    52  
    53  // close cleans up any resources associated with the given binary instance.
    54  func (b *binary) close() {
    55  	C.mongocrypt_binary_destroy(b.wrapped)
    56  }