callWithBuffer function

Uint8List? callWithBuffer(
  1. BufferCallback fn, {
  2. int? maxSize,
  3. int? initialSize,
})

Calls a buffer callback function with dynamically sized buffers.

Starts with initialSize or initialBufferSize and doubles the buffer size if the callback returns -2 (buffer too small), up to maxSize or maxBufferSize.

When maxSize is null, maxBufferSize is used. When initialSize is null, initialBufferSize is used. Returns the data as Uint8List on success, null on failure.

Implementation

Uint8List? callWithBuffer(BufferCallback fn, {int? maxSize, int? initialSize}) {
  final limit = maxSize ?? maxBufferSize;
  var size = initialSize ?? initialBufferSize;
  while (size <= limit) {
    final buf = malloc<ffi.Uint8>(size);
    final outWritten = malloc<ffi.Uint32>()..value = 0;
    try {
      final code = fn(buf, size, outWritten);
      if (code == 0) {
        final n = outWritten.value;
        if (n == 0) {
          return Uint8List(0);
        }
        return Uint8List.fromList(buf.asTypedList(n));
      }
      if (code == -2) {
        size *= 2;
        continue;
      }
      return null;
    } finally {
      malloc
        ..free(buf)
        ..free(outWritten);
    }
  }
  return null;
}