SodiumPointer<T extends NativeType>.alloc constructor

SodiumPointer<T extends NativeType>.alloc(
  1. LibSodiumFFI sodium, {
  2. int count = 1,
  3. MemoryProtection memoryProtection = MemoryProtection.readWrite,
  4. bool zeroMemory = false,
})

Allocates new memory using the libsodium APIs.

The sodium parameter is the reference to the libsodium C API. By default, the pointer will have a count of 1 - meaning it is exactly sizeOf<T> bytes wide. If you set count to a higher value, it will be sizeOf<T> * count.

If you want to immediately set the memoryProtection level, you can do so by changing the parameter to a different value. By default, the pointer is not protected and thus is writable.

By default, the memory is filled with 0xdb bytes. If you want to fill it with 0x00 instead, simply set zeroMemory to true.

Internally, sodium_malloc or sodium_allocarray are used to allocate the memory.

See https://libsodium.gitbook.io/doc/memory_management#guarded-heap-allocations

Implementation

factory SodiumPointer.alloc(
  LibSodiumFFI sodium, {
  int count = 1,
  MemoryProtection memoryProtection = MemoryProtection.readWrite,
  bool zeroMemory = false,
}) {
  RangeError.checkNotNegative(count, 'count');

  final elementSize = _StaticallyTypedSizeOf.staticSizeOf<T>();
  late final SodiumPointer<T> ptr;
  if (count != 1) {
    ptr = SodiumPointer.raw(
      sodium,
      sodium.sodium_allocarray(count, elementSize).cast(),
      count,
    );
  } else {
    ptr = SodiumPointer.raw(
      sodium,
      sodium.sodium_malloc(elementSize).cast(),
      1,
    );
  }

  try {
    if (zeroMemory) {
      ptr.zeroMemory();
    }
    return ptr..memoryProtection = memoryProtection;
  } catch (e) {
    ptr.dispose();
    rethrow;
  }
}