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.
64 lines • 2.53 kB
JavaScript
import { _Debug } from "./_debug.js";
import { arrayContains } from "../array/impl/array-contains.js";
import { stringConcat2 } from "../string/impl/string-concat-2.js";
/**
* @public
* Provides a view of an object that can be invalidated, causing attempts to access it to error in `_BUILD.DEBUG`.
*
* @remarks
* Allows the specification of `safeKeys`, accessing of these is not an error regardless of invalidation state.
*/
export class DebugProtectedView {
constructor(debugInfo, safeKeys = []) {
this.debugInfo = debugInfo;
this.safeKeys = safeKeys;
this.validViews = new Set();
}
debugOnAllocate() {
this.invalidate();
}
invalidate() {
this.validViews.clear();
}
createProtectedView(view) {
this.validViews.add(view);
return new Proxy(view, {
get: (_target, property) => {
if (property === DebugProtectedView.originalViewKey) {
return view;
}
if (property === DebugProtectedView.isViewValidKey) {
return this.validViews.has(view);
}
if (property === DebugProtectedView.debugMessageKey) {
return `ProtectedView view invalidated - ${this.debugInfo}`;
}
if (!this.validViews.has(view)) {
_Debug.assert(arrayContains(this.safeKeys, property), `ProtectedView view invalidated - ${this.debugInfo}`);
}
if (typeof view[property] == "function") {
return view[property].bind(view);
}
return view[property];
}
});
}
static unwrapProtectedView(view) {
const hiddenView = view[DebugProtectedView.originalViewKey];
if (hiddenView == null) {
// it's not a proxy
return view;
}
if (!view[DebugProtectedView.isViewValidKey]) {
_Debug.error(view[DebugProtectedView.debugMessageKey]);
}
return hiddenView;
}
}
DebugProtectedView.createTypedArrayView = (instanceName) => {
return new DebugProtectedView(stringConcat2(instanceName, " - memory resize danger, refresh instance with getInstance"), ["BYTES_PER_ELEMENT"]);
};
DebugProtectedView.isViewValidKey = Symbol("isViewValid");
DebugProtectedView.originalViewKey = Symbol("originalView");
DebugProtectedView.debugMessageKey = Symbol("debugMessage");
//# sourceMappingURL=debug-protected-view.js.map