allocAligned function

AlignedAlloc allocAligned(
  1. int bytes, {
  2. int align = kLiteRtHostMemoryAlignment,
})

Allocate bytes of host memory and return a AlignedAlloc whose .aligned pointer is aligned to align bytes (default 64, the LITERT_HOST_MEMORY_BUFFER_ALIGNMENT value).

Dart's calloc returns at most 16-byte aligned memory on most ABIs, which is below LiteRT's 64-byte requirement. We over-allocate by align + sizeof(void*) and round the pointer up.

Implementation

AlignedAlloc allocAligned(int bytes, {int align = kLiteRtHostMemoryAlignment}) {
  final raw = calloc<Uint8>(bytes + align + sizeOf<IntPtr>());
  final mask = align - 1;
  final aligned =
      Pointer<Uint8>.fromAddress((raw.address + align) & ~mask);
  return AlignedAlloc(raw, aligned);
}