UNPKG

@chainsafe/ssz

Version:
74 lines 2.73 kB
import { getNodesAtDepth, packedNodeRootsToBytes, packedRootsBytesToNode } from "@chainsafe/persistent-merkle-tree"; import { maxChunksToDepth } from "../util/merkleize.js"; import { namedClass } from "../util/named.js"; import { ByteArrayType } from "./byteArray.js"; /** * ByteVector: Immutable alias of Vector[byte, N] * - Notation: `ByteVector[N]` * - Value: `Uint8Array` * - View: `Uint8Array` * - ViewDU: `Uint8Array` * * ByteVector is an immutable value which is represented by a Uint8Array for memory efficiency and performance. * Note: Consumers of this type MUST never mutate the `Uint8Array` representation of a ByteVector. * * For a `ByteVectorType` with mutability, use `VectorBasicType(byteType)` */ export class ByteVectorType extends ByteArrayType { lengthBytes; typeName; // Immutable characteristics depth; chunkDepth; fixedSize; minSize; maxSize; maxChunkCount; isList = false; constructor(lengthBytes, opts) { super(); this.lengthBytes = lengthBytes; if (lengthBytes === 0) throw Error("Vector length must be > 0"); this.typeName = opts?.typeName ?? `ByteVector[${lengthBytes}]`; this.maxChunkCount = Math.ceil(this.lengthBytes / 32); this.chunkDepth = maxChunksToDepth(this.maxChunkCount); this.depth = this.chunkDepth; this.fixedSize = this.lengthBytes; this.minSize = this.fixedSize; this.maxSize = this.fixedSize; } static named(limitBits, opts) { return new (namedClass(ByteVectorType, opts.typeName))(limitBits, opts); } // Views: inherited from ByteArrayType // Serialization + deserialization value_serializedSize() { return this.fixedSize; } // value_* inherited from ByteArrayType tree_serializedSize() { return this.fixedSize; } tree_serializeToBytes(output, offset, node) { const nodes = getNodesAtDepth(node, this.chunkDepth, 0, this.maxChunkCount); packedNodeRootsToBytes(output.dataView, offset, this.fixedSize, nodes); return offset + this.fixedSize; } tree_deserializeFromBytes(data, start, end) { this.assertValidSize(end - start); return packedRootsBytesToNode(this.chunkDepth, data.dataView, start, end); } tree_getByteLen() { return this.lengthBytes; } // Merkleization: inherited from ByteArrayType // Proofs: inherited from BitArrayType // JSON: inherited from ByteArrayType assertValidSize(size) { if (size !== this.lengthBytes) { throw Error(`ByteVector invalid size ${size} expected ${this.lengthBytes}`); } } } //# sourceMappingURL=byteVector.js.map