mgpuReadAsyncInt8 function
Future<void>
mgpuReadAsyncInt8(
- MGPUBuffer buffer,
- Int8List outputData, {
- int readElements = 0,
- int elementOffset = 0,
Asynchronous read functions for multiple types. Each function allocates native memory, calls ccall with async:true, then copies the data from the WebAssembly heap into the given Dart TypedData.
Implementation
Future<void> mgpuReadAsyncInt8(
MGPUBuffer buffer,
Int8List outputData, {
int readElements = 0,
int elementOffset = 0,
}) async {
final int bytesPerElem = Int8List.bytesPerElement;
// Calculate element count based on outputData size if readElements is 0
final int elementsToRead = (readElements > 0)
? readElements
: (outputData.length - elementOffset);
final int sizeToAllocate =
elementsToRead * bytesPerElem; // Allocate based on elements
if (elementsToRead <= 0 ||
elementOffset < 0 ||
elementOffset >= outputData.length)
return; // Nothing to read or invalid offset
final JSNumber ptr = _malloc(sizeToAllocate.toJS);
final int startIndex = ptr.toDartInt; // Byte index for heap copy
try {
// Add bounds check
if (startIndex < 0 || startIndex + sizeToAllocate > _heapU8.length) {
throw StateError(
'Int8 buffer read would exceed heap bounds: '
'trying to read $elementsToRead elements at index $startIndex '
'but heap size is ${_heapU8.length}',
);
}
await ccall(
"mgpuReadSyncInt8".toJS, // Use sync C++ function
"void".toJS, // C++ function returns void
["number", "number", "number", "number"].toJSDeep,
[buffer, ptr, elementsToRead.toJS, elementOffset.toJS].toJSDeep,
{"async": true}.toJSDeep,
).toDart;
// Copy the data from WASM heap
// startIndex is the byte offset, elementsToRead is the count
final output = _heapI8.sublist(startIndex, startIndex + elementsToRead);
outputData.setAll(elementOffset, output);
} finally {
_free(ptr);
}
}