mgpuReadAsyncUint8 function
Future<void>
mgpuReadAsyncUint8(
- MGPUBuffer buffer,
- Uint8List outputData, {
- int readElements = 0,
- int elementOffset = 0,
Implementation
Future<void> mgpuReadAsyncUint8(
MGPUBuffer buffer,
Uint8List outputData, {
int readElements = 0,
int elementOffset = 0,
}) async {
final int bytesPerElem = Uint8List.bytesPerElement;
final int elementsToRead = (readElements > 0)
? readElements
: (outputData.length - elementOffset);
final int sizeToAllocate = elementsToRead * bytesPerElem;
if (elementsToRead <= 0 ||
elementOffset < 0 ||
elementOffset >= outputData.length)
return;
final JSNumber ptr = _malloc(sizeToAllocate.toJS);
final int startIndex = ptr.toDartInt; // Byte index
try {
// Add bounds check for the heap access
if (startIndex < 0 || startIndex + sizeToAllocate > _heapU8.length) {
throw StateError(
'Uint8 buffer read would exceed heap bounds: '
'trying to read $elementsToRead elements at index $startIndex '
'but heap size is ${_heapU8.length}',
);
}
await ccall(
"mgpuReadSyncUint8".toJS, // Use sync C++ function
"void".toJS,
["number", "number", "number", "number"].toJSDeep,
[buffer, ptr, elementsToRead.toJS, elementOffset.toJS].toJSDeep,
{"async": true}.toJSDeep,
).toDart;
final output = _heapU8.sublist(startIndex, startIndex + elementsToRead);
outputData.setAll(elementOffset, output);
} finally {
_free(ptr);
}
}