using<R> function

R using<R>(
  1. R computation(
    1. Arena
    ), [
  2. Allocator wrappedAllocator = calloc
])

Runs computation with a new Arena, and releases all allocations at the end.

If the return value of computation is a Future, all allocations are released when the future completes.

If the isolate is shut down, through Isolate.kill(), resources are not cleaned up.

Implementation

R using<R>(R Function(Arena) computation,
    [Allocator wrappedAllocator = calloc]) {
  final arena = Arena(wrappedAllocator);
  bool isAsync = false;
  try {
    final result = computation(arena);
    if (result is Future) {
      isAsync = true;
      return (result.whenComplete(arena.releaseAll) as R);
    }
    return result;
  } finally {
    if (!isAsync) {
      arena.releaseAll();
    }
  }
}