insertBorrowHandle method
Creates a canonical borrowed handle owned by scope.
The alias keeps sourceHandle live, exposes the same nominal resource and
representation, and never runs the resource destructor. Dropping the
alias releases both the source handle and the original borrow scope even
when another task performs the drop.
Implementation
int insertBorrowHandle(
int sourceHandle,
WASIComponentCanonicalBorrowScope scope,
) {
final source = _entryForHandle(sourceHandle);
if (source == null) {
throw StateError(
'Unknown WASI component resource handle: $sourceHandle.',
);
}
_validateScopeAccess(sourceHandle, source);
final ambientScope = _currentScope;
if (ambientScope?.isClosed ?? false) {
throw StateError(
'Cannot allocate a WASI component resource after its scope closed.',
);
}
final aliasScope = ambientScope ?? source.scope;
scope.addBorrow();
source.borrowCount++;
try {
final slotIndex = _allocateSlot();
final handle = _allocateHandle();
final slot = _slots[slotIndex];
slot.entry = source.borrowedAlias(
_WASIComponentCanonicalBorrow(source, scope),
aliasScope,
);
_handleToSlot[handle] = slotIndex;
_activeCount++;
aliasScope?._handles.add(handle);
_recordResourceType(source.type, aliasScope);
return handle;
} catch (_) {
source.borrowCount--;
scope.releaseBorrow();
rethrow;
}
}