UNPKG

@hazae41/box

Version:

Rust-like Box and similar objects for TypeScript

132 lines (128 loc) 2.98 kB
'use strict'; var index = require('../deferred/index.cjs'); var _a; class MovedError extends Error { #class = _a; name = this.#class.name; constructor() { super(`Resource is moved`); } } _a = MovedError; /** * A movable reference */ class Move { value; clean; #moved = false; /** * An movable reference * @param value */ constructor(value, clean) { this.value = value; this.clean = clean; } static wrap(value) { return new Move(value, value); } static from(value) { return new Move(value.get(), value); } static with(value, clean) { return new Move(value, new index.Deferred(() => clean(value))); } [Symbol.dispose]() { if (this.#moved) return; this.clean[Symbol.dispose](); } async [Symbol.asyncDispose]() { this[Symbol.dispose](); } get moved() { return this.#moved; } /** * Get the value * @returns T */ get() { return this.value; } /** * Get the value or null-like if not owned * @returns T or null-like if not owned */ getOrNull() { if (this.#moved) return; return this.value; } /** * Get the value or throw if not owned * @returns T * @throws NotOwnedError if not owned */ getOrThrow() { if (this.#moved) throw new MovedError(); return this.value; } checkOrNull() { if (this.#moved) return; return this; } checkOrThrow() { if (this.#moved) throw new MovedError(); return this; } /** * Get the value and set this as moved or null-like if not owned * @returns T or null-like if not owned */ unwrapOrNull() { if (this.#moved) return; this.#moved = true; return this.value; } /** * Get the value and set this as moved or throw if not owned * @returns T * @throws DroppedError if not owned */ unwrapOrThrow() { if (this.#moved) throw new MovedError(); this.#moved = true; return this.value; } /** * Move the value to a new Unpin and set this one as moved or null-like if already moved * @returns Unpin<T> or null-like if moved */ moveOrNull() { if (this.#moved) return; this.#moved = true; return new Move(this.value, this.clean); } /** * Move the value to a new Unpin and set this one as moved or throw if already moved * @returns Unpin<T> * @throws DroppedError if already moved */ moveOrThrow() { if (this.#moved) throw new MovedError(); this.#moved = true; return new Move(this.value, this.clean); } } exports.Move = Move; exports.MovedError = MovedError; //# sourceMappingURL=index.cjs.map