@hazae41/box
Version:
Rust-like Box and similar objects for TypeScript
84 lines (81 loc) • 1.94 kB
JavaScript
import { Deferred } from '../deferred/index.mjs';
import { Ref } from '../ref/index.mjs';
var _a;
class BorrowedError extends Error {
#class = _a;
name = this.#class.name;
constructor() {
super(`Resource is borrowed`);
}
}
_a = BorrowedError;
/**
* A borrowable reference
* @param value
*/
class Borrow {
value;
clean;
#borrowed = false;
constructor(value, clean) {
this.value = value;
this.clean = clean;
}
static wrap(value) {
return new Borrow(value, value);
}
static from(value) {
return new Borrow(value.get(), value);
}
static with(value, clean) {
return new Borrow(value, new Deferred(() => clean(value)));
}
[Symbol.dispose]() {
this.clean[Symbol.dispose]();
}
async [Symbol.asyncDispose]() {
this[Symbol.dispose]();
}
get borrowed() {
return this.#borrowed;
}
get() {
return this.value;
}
getOrNull() {
if (this.#borrowed)
return;
return this.value;
}
getOrThrow() {
if (this.#borrowed)
throw new BorrowedError();
return this.value;
}
checkOrNull() {
if (this.#borrowed)
return;
return this;
}
checkOrThrow() {
if (this.#borrowed)
throw new BorrowedError();
return this;
}
borrowOrNull() {
if (this.#borrowed)
return;
this.#borrowed = true;
const dispose = () => { this.#borrowed = false; };
return new Ref(this.value, new Deferred(dispose));
}
borrowOrThrow() {
if (this.#borrowed)
throw new BorrowedError();
this.#borrowed = true;
const dispose = () => { this.#borrowed = false; };
return new Ref(this.value, new Deferred(dispose));
}
}
export { Borrow, BorrowedError };
//# sourceMappingURL=index.mjs.map