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.

46 lines 1.77 kB
import { ReferenceCountedNode } from "../../lifecycle/reference-counted-node.js"; import { lifecycleStack } from "./lifecycle-stack.js"; /** * @public * Automatically releases handles when objects are garbage collected. The implementation relies on `FinalizationRegistry`, * which comes with a large number of health warnings, you probably shouldn't use it in production for anything important... * * Do not use this for testing of library functions, instead use {@link ReferenceCountedStrategy}. */ export class AutomaticGcStrategy { constructor() { this.finalizationRegistry = new FinalizationRegistry((resourceHandle) => { resourceHandle.onFreeChannel.emit(); resourceHandle.getLinked().unlinkAll(); }); } createNode(owner) { // our reference counted node is a hybrid (there's no RAII...), so we have the object graph here // this means we don't need worry about pointer cycles, the JS garbage collector is doing the heavy lifting for us owner !== null && owner !== void 0 ? owner : (owner = lifecycleStack.getTop()); const newNode = new ReferenceCountedNode(); owner.getLinked().link(newNode); newNode.onReleased(); return newNode; } /** * @internal */ createRootNode() { return new ReferenceCountedNode(); } onSharedPointerCreated(sharedPtr) { // this strategy doesn't require this extra metadata this.onManagedObjectCreated(sharedPtr); } onManagedObjectCreated(object) { this.finalizationRegistry.register(object, object.resourceHandle); } /** * @internal */ setWrapper() { // not required... } } //# sourceMappingURL=automatic-gc-strategy.js.map