UNPKG

@hazae41/box

Version:

Rust-like Box and similar objects for TypeScript

113 lines (110 loc) 2.51 kB
'use strict'; var _a, _b, _c; class OwnedError extends Error { #class = _a; name = this.#class.name; constructor() { super(`Resource is owned`); } } _a = OwnedError; class BorrowedError extends Error { #class = _b; name = this.#class.name; constructor() { super(`Resource is borrowed`); } } _b = BorrowedError; class DroppedError extends Error { #class = _c; name = this.#class.name; constructor() { super(`Resource is dropped`); } } _c = DroppedError; class Borrow { parent; #state = "owned"; constructor(parent) { this.parent = parent; } [Symbol.dispose]() { if (this.dropped) return; if (this.owned) this.parent.returnOrThrow(); this.#state = "dropped"; } async [Symbol.asyncDispose]() { this[Symbol.dispose](); } get value() { return this.parent.value; } get owned() { return this.#state === "owned"; } get borrowed() { return this.#state === "borrowed"; } get dropped() { return this.#state === "dropped"; } get() { return this.value; } getOrNull() { if (!this.owned) return; return this.value; } getOrThrow() { if (this.borrowed) throw new BorrowedError(); if (this.dropped) throw new DroppedError(); return this.value; } checkOrNull() { if (!this.owned) return; return this; } checkOrThrow() { if (this.borrowed) throw new BorrowedError(); if (this.dropped) throw new DroppedError(); return this; } borrowOrNull() { if (!this.owned) return; this.#state = "borrowed"; return new Borrow(this); } borrowOrThrow() { if (this.borrowed) throw new BorrowedError(); if (this.dropped) throw new DroppedError(); this.#state = "borrowed"; return new Borrow(this); } returnOrThrow() { if (this.owned) throw new OwnedError(); if (this.borrowed) this.#state = "owned"; else if (this.dropped) this.parent.returnOrThrow(); return; } } exports.Borrow = Borrow; exports.BorrowedError = BorrowedError; exports.DroppedError = DroppedError; exports.OwnedError = OwnedError; //# sourceMappingURL=index.cjs.map