UNPKG

@chainsafe/ssz

Version:

Simple Serialize

87 lines 3.34 kB
import { concatGindices, toGindex } from "@chainsafe/persistent-merkle-tree"; import { byteArrayEquals, fromHexString, toHexString } from "../util/byteArray.js"; import { BitArrayTreeView } from "../view/bitArray.js"; import { BitArrayTreeViewDU } from "../viewDU/bitArray.js"; import { getBlocksBytes } from "./byteArray.js"; import { CompositeType, LENGTH_GINDEX } from "./composite.js"; /** * BitArray: ordered array collection of boolean values * - Value: `BitArray`, @see BitArray for a justification of its memory efficiency and performance * - View: `BitArrayTreeView` * - ViewDU: `BitArrayTreeViewDU` */ export class BitArrayType extends CompositeType { isViewMutable = true; getView(tree) { return new BitArrayTreeView(this, tree); } getViewDU(node) { return new BitArrayTreeViewDU(this, node); } commitView(view) { return view.node; } commitViewDU(view, hcOffset = 0, hcByLevel = null) { view.commit(hcOffset, hcByLevel); return view.node; } cacheOfViewDU(view) { return view.cache; } // Merkleization getBlocksBytes(value) { // reallocate this.blocksBuffer if needed if (value.uint8Array.length > this.blocksBuffer.length) { const chunkCount = Math.ceil(value.bitLen / 8 / 32); this.blocksBuffer = new Uint8Array(Math.ceil(chunkCount / 2) * 64); } return getBlocksBytes(value.uint8Array, this.blocksBuffer); } // Proofs getPropertyGindex() { // Stop navigating below this type. Must only request complete data return null; } getPropertyType() { /* istanbul ignore next - unreachable code, getPropertyGindex null return prevents this call */ throw Error("Must only request BitArray complete data"); } getIndexProperty() { /* istanbul ignore next - unreachable code, getPropertyGindex null return prevents this call */ throw Error("Must only request BitArray complete data"); } tree_fromProofNode(node) { return { node, done: true }; } tree_getLeafGindices(rootGindex, rootNode) { const byteLen = this.tree_getByteLen(rootNode); const chunkCount = Math.ceil(byteLen / 32); const startIndex = concatGindices([rootGindex, toGindex(this.depth, BigInt(0))]); const gindices = new Array(chunkCount); for (let i = 0, gindex = startIndex; i < chunkCount; i++, gindex++) { gindices[i] = gindex; } // include the length chunk if (this.isList) { gindices.push(concatGindices([rootGindex, LENGTH_GINDEX])); } return gindices; } // JSON fromJson(json) { const uint8Array = fromHexString(json); const dataView = new DataView(uint8Array.buffer, uint8Array.byteOffset, uint8Array.byteLength); // value_deserializeFromBytes MUST validate length (limit, or length) return this.value_deserializeFromBytes({ uint8Array, dataView }, 0, uint8Array.length); } toJson(value) { return toHexString(this.serialize(value)); } clone(value) { return value.clone(); } equals(a, b) { return a.bitLen === b.bitLen && byteArrayEquals(a.uint8Array, b.uint8Array); } } //# sourceMappingURL=bitArray.js.map