UNPKG

rc-js-util

Version:

A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.

72 lines 3.04 kB
import { nullPtr } from "../emscripten/null-pointer.js"; import { DebugProtectedView } from "../../debug/debug-protected-view.js"; import { _Debug } from "../../debug/_debug.js"; import { numberGetHexString } from "../../number/impl/number-get-hex-string.js"; import { NestedError } from "../../error-handling/nested-error.js"; import { WasmErrorCause } from "../wasm-error-cause.js"; import { ESharedObjectOwnerKind, SharedObjectCleanup } from "./shared-object-cleanup.js"; /** * @public * {@inheritDoc ISharedMemoryBlock} */ export class SharedMemoryBlock { static createOne(wrapper, bindToReference, byteSize, allocationFailThrows = true) { _BUILD.DEBUG && wrapper.debugUtils.onAllocate.emit(); const pointer = wrapper.instance._jsUtilMalloc(byteSize); if (pointer == nullPtr) { if (allocationFailThrows) { throw new NestedError("Failed to allocate memory for shared memory block.", WasmErrorCause.allocationFailure); } else { return null; } } return new SharedMemoryBlock(wrapper, bindToReference, pointer, byteSize); } getWrapper() { return this.wrapper; } getDataView() { if (_BUILD.DEBUG) { _Debug.assert(!this.resourceHandle.getIsDestroyed(), "use after free"); return this.wrapper.debugUtils.protectedViews .getValue(this.resourceHandle) .createProtectedView(this.impl.dataView); } else { return this.impl.dataView; } } constructor(wrapper, owner, pointer, byteSize) { this.wrapper = wrapper; this.resourceHandle = wrapper.lifecycleStrategy.createNode(owner); this.pointer = pointer; this.byteSize = byteSize; this.impl = new SharedMemoryBlockImpl(this, pointer, byteSize); SharedObjectCleanup.registerCleanup(this, this.impl, new SharedObjectCleanup.Options("SharedMemoryBlock", _BUILD.DEBUG ? new DebugProtectedView(`SharedMemoryBlock - memory resize danger: don't hold reference to the DataView ${numberGetHexString(pointer)}`) : null, ESharedObjectOwnerKind.Freeable)); } } class SharedMemoryBlockImpl extends SharedObjectCleanup { constructor(sharedMemoryBlock, pointer, byteSize) { super(sharedMemoryBlock, ESharedObjectOwnerKind.Freeable); this.pointer = pointer; this.byteSize = byteSize; this.dataView = this.recreateDataView(); this.wrapper.memoryResize.addListener(this); } onFree() { super.onFree(); this.wrapper.memoryResize.removeListener(this); } onMemoryResize() { if (this.wrapper == null) { _BUILD.DEBUG && _Debug.error("object has been destroyed"); return; } this.dataView = this.recreateDataView(); } recreateDataView() { return new DataView(this.wrapper.memory.buffer, this.pointer, this.byteSize); } } //# sourceMappingURL=shared-memory-block.js.map