@metamask/ocap-kernel
Version:
OCap kernel core components
76 lines • 2.31 kB
JavaScript
import { keySearch } from "../utils/key-search.mjs";
/**
* Create an in-memory VatKVStore for a vat, backed by a Map and tracking
* changes so that they can be reported at the end of a crank.
*
* @param state - The state to begin with.
*
* @returns a VatKVStore wrapped around `state`.
*/
export function makeVatKVStore(state) {
const sets = new Map();
const deletes = new Set();
let keyCache = null;
let lastNextKey = null;
let lastNextKeyIndex = -1;
return {
get(key) {
return state.get(key);
},
getRequired(key) {
const result = state.get(key);
if (result) {
return result;
}
throw Error(`no value matching key '${key}'`);
},
getNextKey(key) {
keyCache ?? (keyCache = Array.from(state.keys()).sort());
const index = lastNextKey === key ? lastNextKeyIndex : keySearch(keyCache, key);
if (index < 0) {
lastNextKey = null;
lastNextKeyIndex = -1;
return undefined;
}
lastNextKey = keyCache[index];
if (key < lastNextKey) {
lastNextKeyIndex = index;
return lastNextKey;
}
else {
if (index + 1 >= keyCache.length) {
lastNextKey = null;
lastNextKeyIndex = -1;
return undefined;
}
else {
lastNextKey = keyCache[index + 1];
lastNextKeyIndex = index + 1;
return lastNextKey;
}
}
},
set(key, value) {
state.set(key, value);
sets.set(key, value);
deletes.delete(key);
keyCache = null;
},
delete(key) {
state.delete(key);
sets.delete(key);
deletes.add(key);
keyCache = null;
},
checkpoint() {
const result = [
Array.from(sets.entries()),
Array.from(deletes),
];
sets.clear();
deletes.clear();
return result;
},
};
}
//# sourceMappingURL=vat-kv-store.mjs.map