Bio.fromBytes constructor

Bio.fromBytes(
  1. OpenSslContext context,
  2. Uint8List bytes
)

Creates a BIO from a memory buffer (Uint8List).

Implementation

factory Bio.fromBytes(OpenSslContext context, Uint8List bytes) {
  // We need to copy bytes to C memory because BIO_new_mem_buf can take a read-only buffer,
  // but if we want it to be safe, we might allocate.
  // However, BIO_new_mem_buf(buf, len) doesn't copy if len is positive?
  // "If len is -1, then buf is assumed to be null terminated... If len is positive, then buf is used."
  // It creates a *read only* bio if the buffer is const, but usually it's better to create a writable memory bio and write to it
  // if we want to own the memory in the BIO.

  // Simplest: Create a memory BIO (writeable) and write data into it.
  final bio = context.bindings.BIO_new(context.bindings.BIO_s_mem());
  if (bio == nullptr) throw OpenSslException('Failed to create BIO');

  final wrapper = Bio._(context, bio);

  final buffer = calloc<Uint8>(bytes.length);
  try {
    buffer.asTypedList(bytes.length).setAll(0, bytes);
    final written = context.bindings.BIO_write(bio, buffer.cast(), bytes.length);
    if (written <= 0) {
      throw OpenSslException('Failed to write to BIO');
    }
  } finally {
    calloc.free(buffer);
  }

  return wrapper;
}