...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/binary.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt

     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  /*
    13  #include <stdlib.h>
    14  #include <mongocrypt.h>
    15  */
    16  import "C"
    17  import (
    18  	"unsafe"
    19  )
    20  
    21  // binary is a wrapper type around a mongocrypt_binary_t*
    22  type binary struct {
    23  	p       *C.uint8_t
    24  	wrapped *C.mongocrypt_binary_t
    25  }
    26  
    27  // newBinary creates an empty binary instance.
    28  func newBinary() *binary {
    29  	return &binary{
    30  		wrapped: C.mongocrypt_binary_new(),
    31  	}
    32  }
    33  
    34  // newBinaryFromBytes creates a binary instance from a byte buffer.
    35  func newBinaryFromBytes(data []byte) *binary {
    36  	if len(data) == 0 {
    37  		return newBinary()
    38  	}
    39  
    40  	// TODO: Consider using runtime.Pinner to replace the C.CBytes after using go1.21.0.
    41  	addr := (*C.uint8_t)(C.CBytes(data)) // uint8_t*
    42  	dataLen := C.uint32_t(len(data))     // uint32_t
    43  	return &binary{
    44  		p:       addr,
    45  		wrapped: C.mongocrypt_binary_new_from_data(addr, dataLen),
    46  	}
    47  }
    48  
    49  // toBytes converts the given binary instance to []byte.
    50  func (b *binary) toBytes() []byte {
    51  	dataPtr := C.mongocrypt_binary_data(b.wrapped) // C.uint8_t*
    52  	dataLen := C.mongocrypt_binary_len(b.wrapped)  // C.uint32_t
    53  
    54  	return C.GoBytes(unsafe.Pointer(dataPtr), C.int(dataLen))
    55  }
    56  
    57  // close cleans up any resources associated with the given binary instance.
    58  func (b *binary) close() {
    59  	if b.p != nil {
    60  		C.free(unsafe.Pointer(b.p))
    61  	}
    62  	C.mongocrypt_binary_destroy(b.wrapped)
    63  }
    64  

View as plain text