acquire method

Future<void> acquire(
  1. int bytes
)

Acquire bytes worth of memory. Waits if capacity is exceeded.

Implementation

Future<void> acquire(int bytes) async {
  // System-memory probing is opt-in: with [safetyMarginBytes] == 0 the gate
  // is a pure fixed byte budget. That matters for PER-CHUNK gating (Step 1),
  // where polling system memory on every chunk would spawn a `vm_stat`
  // subprocess per 1 MB and serialise dispatch — defeating the concurrency.
  if (safetyMarginBytes > 0) {
    final availableMemory = await _getAvailableMemory();
    if (availableMemory != null &&
        availableMemory < safetyMarginBytes + bytes) {
      // Wait for memory to free up
      final completer = Completer<void>();
      _waiters.add(_MemoryWaiter(bytes: bytes, completer: completer));
      return completer.future;
    }
  }

  if (_currentBytes + bytes > maxBytes) {
    final completer = Completer<void>();
    _waiters.add(_MemoryWaiter(bytes: bytes, completer: completer));
    return completer.future;
  }

  _currentBytes += bytes;
}