@hazae41/box
Version:
Rust-like Box and similar objects for TypeScript
129 lines (126 loc) • 2.94 kB
JavaScript
import { Deferred } from '../deferred/index.mjs';
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 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);
}
}
export { Move, MovedError };
//# sourceMappingURL=index.mjs.map