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.
68 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DebugProtectedView = void 0;
const _debug_js_1 = require("./_debug.js");
const array_contains_js_1 = require("../array/impl/array-contains.js");
const string_concat_2_js_1 = require("../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.
*/
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_js_1._Debug.assert((0, array_contains_js_1.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_js_1._Debug.error(view[DebugProtectedView.debugMessageKey]);
}
return hiddenView;
}
}
exports.DebugProtectedView = DebugProtectedView;
DebugProtectedView.createTypedArrayView = (instanceName) => {
return new DebugProtectedView((0, string_concat_2_js_1.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