+// 🎐📦 ハブ ∷ mod.js
+// ====================================================================
+//
+// Copyright © 2022 Lady [@ Lady’s Computer].
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
+
+/** 2^53 − 1. */
+const MAX_SAFE_INTEGER = Number((1n << 53n) - 1n);
+
+/**
+ * An object which can be built up in an arraylike fashion.
+ *
+ * This class copies the `from` and `of` static methods of Array to
+ * dodge Array limitations on `length`.
+ */
+class MockArray extends Array {
+ /** Constructs a new MockArray as an ordinary (non·exotic) object. */
+ constuctor(...values) {
+ const array = Object.create(MockArray.prototype, {
+ length: {
+ configurable: false,
+ enumerable: false,
+ value: 0,
+ writable: true,
+ },
+ });
+ const numberOfArgs = values.length;
+ if (numberOfArgs == 0) {
+ // No arguments were supplied.
+ return array;
+ } else if (numberOfArgs == 1) {
+ // One argument was supplied.
+ const len = values[0];
+ if (typeof len != "number") {
+ // The argument was not a number.
+ return Object.assign(array, {
+ 0: len,
+ length: 1,
+ });
+ } else {
+ // The argument was a number, and needs to be treated as a
+ // length.
+ const intLen = toLength(len); // allow larger length than Array
+ if (intLen != len) {
+ // The provided length was invalid.
+ throw new RangeError("ハブ: Invalid length.");
+ } else {
+ // The provided length was valid.
+ return Object.assign(array, { length: len });
+ }
+ }
+ } else {
+ // More than one argument was supplied.
+ return Object.assign(array, values, { length: numberOfArgs });
+ }
+ }
+}
+
+/**
+ * A generic container for lists of binary data of defined size.
+ *
+ * Values can be anywhere from 1 to 64 bits wide, although this class
+ * is not advantageous for widths larger than 21. Regardless of size,
+ * values will be represented as big·ints.
+ *
+ * This class trades computational efficiency getting and setting
+ * values for storage efficiency (ability to compact many values in a
+ * tight space); it is subsequently targeted at larger datasets which
+ * need to be available in memory but which don’t often need to be
+ * read.
+ *
+ * A note on limits: The upper limit for the length of an ordinary
+ * Ecmascript array of integers is 2^32 − 1. Each integer has 32 bytes
+ * which are readily accessible via bitwise operations, so that makes
+ * for 137 438 953 440 total bits accessible in an ordinary array.
+ * In contrast, an array buffer has a higher maximum byte length of
+ * 2^53 − 1, but obviously only allows for the storage of 8 bits per
+ * byte, for 72 057 594 037 927 928 total accessible bits. For
+ * technical reasons, the maximum total length of the ハブ instance is
+ * also capped to 2^53 − 1 (relevant for bit widths of less than 8).
+ *
+ * While this class uses an array buffer for its storage, and is
+ * conceptually more similar to Ecmascript typed arrays, it is an array
+ * exotic object and inherits from the ordinary Array class.
+ */
+export default class ハブ extends Array {
+ /**
+ * Constructs a new ハブ with items of the provided size (in bits).
+ *
+ * The first argument must be the number of bits per item. If the
+ * second argument is an array buffer, it is used as the underlying
+ * store, and additional byte offset and length arguments may be
+ * supplied. Otherwise, if the second argument is an object, it is
+ * iterated over in a manner similar to `Array.from`. Otherwise, it
+ * is used as the length.
+ */
+ constructor(bitWidth, ...args) {
+ super(); // sets `length` (unused)
+ const bitsPerItem = validSize(bitWidth);
+ const wordSize = wordSizeByBits[bitsPerItem];
+ const scale = wordSize * 8 / bitsPerItem >> 0;
+ Object.defineProperties(
+ this,
+ {
+ wordScale: { ...unlisted, value: scale },
+ wordSize: { ...unlisted, value: wordSize },
+ bitWidth: { ...unlisted, value: bitsPerItem },
+ },
+ );
+ const length = (() => {
+ if (args.length == 0) {
+ // No additional arguments provided; initialize with zero
+ // length.
+ defineNewBuffer.call(this, 0);
+ return 0;
+ } else {
+ // An additional argument is present.
+ const firstArg = args[0];
+ const bufferByteLength = (() => {
+ try {
+ return Reflect.get(
+ ArrayBuffer.prototype,
+ "byteLength",
+ firstArg,
+ ); // will throw if not an array buffer
+ } catch {
+ return undefined;
+ }
+ })();
+ if (bufferByteLength != null) {
+ // The first additional argument is an array buffer.
+ const offset = toIndex(args[1]);
+ const length = args[2];
+ if (offset % wordSize || offset > bufferByteLength) {
+ // The provided offset exceeds the length of the buffer or is
+ // not divisible by the word size.
+ throw new RangeError("ハブ: Improper byte offset.");
+ } else if (length === undefined) {
+ // There is no provided length.
+ if (bufferByteLength % wordSize) {
+ // The provided buffer is not divisible by the word size.
+ throw new RangeError("ハブ: Improperly sized buffer.");
+ } else {
+ // The entire buffer after the offset should be used.
+ const newByteLength = bufferByteLength - offset;
+ const itemLength = BigInt(newByteLength / wordSize) *
+ BigInt(scale);
+ if (itemLength > MAX_SAFE_INTEGER) {
+ // If the entire buffer is used, it will result in a
+ // length greater than `MAX_SAFE_INTEGER`.
+ throw new RangeError("ハブ: Buffer too large.");
+ } else {
+ // The buffer is sized properly.
+ Object.defineProperties(this, {
+ buffer: { ...unlisted, value: firstArg },
+ byteLength: { ...unlisted, value: newByteLength },
+ byteOffset: { ...unlisted, value: offset },
+ });
+ return Number(itemLength);
+ }
+ }
+ } else {
+ // A length was provided.
+ const newByteLength = toIndex(Math.ceil(length / scale)) *
+ wordSize;
+ const itemLength = toIndex(length);
+ if (offset + newByteLength > bufferByteLength) {
+ // The resulting byte length combined with the offset
+ // exceeds the length of the buffer.
+ throw new RangeError("ハブ: Improper length.");
+ } else {
+ // All of the provided values check out and can be used.
+ Object.defineProperties(this, {
+ buffer: { ...unlisted, value: firstArg },
+ byteLength: { ...unlisted, value: newByteLength },
+ byteOffset: { ...unlisted, value: offset },
+ });
+ return itemLength;
+ }
+ }
+ } else if (
+ typeof firstArg == "function" ||
+ typeof firstArg == "object" && firstArg != null
+ ) {
+ // The first additional argument is an object, but not an
+ // array buffer.
+ const data = MockArray.from(firstArg);
+ const { length } = data;
+ defineNewBuffer.call(
+ this,
+ Math.ceil(length / scale) * wordSize,
+ );
+ for (const [index, datum] of data.entries()) {
+ setItem.call(this, index, datum);
+ }
+ return length;
+ } else {
+ // The first additional argument is a primitive.
+ const length = Math.floor(firstArg);
+ if (isNaN(length) || length == 0) {
+ // The provided argument is zero·like.
+ defineNewBuffer.call(this, 0);
+ return 0;
+ } else {
+ // The provided argument can’t be treated as zero.
+ const neededBytes = Math.ceil(length / scale) * wordSize;
+ if (neededBytes < 0 || neededBytes > MAX_SAFE_INTEGER) {
+ // The provided argument is not a valid length.
+ throw new RangeError(`ハブ: Invalid length: ${firstArg}`);
+ } else {
+ // The provided argument can be treated like a length.
+ defineNewBuffer.call(this, neededBytes);
+ return length;
+ }
+ }
+ }
+ }
+ })();
+ return new Proxy(this, new ハブ·ProxyHandler(length));
+ }
+
+ /**
+ * Returns a new ハブ instance of the provided bit width, generated
+ * in a manner akin to `Array.from()`.
+ */
+ static from(
+ bitWidth,
+ items,
+ mapFn = undefined,
+ thisArg = undefined,
+ ) {
+ return new (this ?? ハブ)(
+ bitWidth,
+ MockArray.from(items, mapFn, thisArg),
+ );
+ }
+
+ /** `isArray` should not be inherited, so is set to undefined. */
+ static isArray = undefined;
+
+ /**
+ * Returns a new ハブ instance of the provided bit width, generated
+ * in a manner akin to `Array.of()`.
+ */
+ static of(bitWidth, ...items) {
+ return new (this ?? ハブ)(bitWidth, MockArray.of(...items));
+ }
+
+ /**
+ * Returns a new ハブ instance of the provided bit width, generated
+ * in a manner akin to `Array.prototype.concat()`.
+ */
+ concat(...items) {
+ const Species = arraySpecies(this);
+ return Species == null ? [].concat(...items) : new Species(
+ Object.assign([], { constructor: MockArray }).concat(...items),
+ );
+ }
+
+ /**
+ * Returns the ハブ constructor, bound to the bit width of this ハブ
+ * instance.
+ */
+ //deno-lint-ignore adjacent-overload-signatures
+ get ["constructor"]() {
+ return ハブ.bind(undefined, this.bitWidth);
+ }
+
+ /** `copyWithin` should not be inherited, so is set to undefined. */
+ get copyWithin() {
+ return undefined;
+ }
+
+ /**
+ * Returns a new ハブ instance of the provided bit width, generated
+ * in a manner akin to `Array.prototype.filter()`.
+ */
+ filter(callbackfn, thisArg = undefined) {
+ const O = new Object(this);
+ const len = toLength(this.length);
+ if (typeof callbackfn != "function") {
+ // The callback is not callable.
+ throw new TypeError("ハブ: Callback must be callable.");
+ } else {
+ // The callback is callable.
+ const Species = arraySpecies(this);
+ const iterator = function* () {
+ for (let k = 0; k < len; ++k) {
+ if (k in O) {
+ // The current index is in the provided value.
+ const kValue = O[k];
+ if (callbackfn.call(thisArg, kValue, k, O)) {
+ // The callback returned true.
+ yield kValue;
+ } else {
+ // The callback returned false.
+ /* do nothing */
+ }
+ } else {
+ // The current index is not in the provided value.
+ /* do nothing */
+ }
+ }
+ }();
+ return Species == null
+ ? Array.from(iterator)
+ : new Species(iterator);
+ }
+ }
+
+ /** `flat` should not be inherited, so is set to undefined. */
+ get flat() {
+ return undefined;
+ }
+
+ /** `flatMap` should not be inherited, so is set to undefined. */
+ get flatMap() {
+ return undefined;
+ }
+
+ /** `pop` should not be inherited, so is set to undefined. */
+ get pop() {
+ return undefined;
+ }
+
+ /** `push` should not be inherited, so is set to undefined. */
+ get push() {
+ return undefined;
+ }
+
+ /** `shift` should not be inherited, so is set to undefined. */
+ get shift() {
+ return undefined;
+ }
+
+ /** `splice` should not be inherited, so is set to undefined. */
+ get splice() {
+ return undefined;
+ }
+
+ /** `unshift` should not be inherited, so is set to undefined. */
+ get unshift() {
+ return undefined;
+ }
+}
+
+/**
+ * A proxy handler for ハブ instances.
+ *
+ * Although ハブ instances are array exotic objects, this handler
+ * overrides the handling of both numeric indices and `length` so that
+ * the exotic array behaviour never actually takes place. Instead, data
+ * is pulled from the object’s associated buffer.
+ */
+class ハブ·ProxyHandler extends Object.assign(
+ function () {},
+ { prototype: Reflect },
+) {
+ /**
+ * The actual number which should be returned as the length of the
+ * proxied value.
+ */
+ #length;
+
+ /**
+ * Constructs a new ハブ·ProxyHandler with the provided numeric
+ * length.
+ */
+ constructor(numericLength) {
+ super();
+ this.#length = Math.min(Number(numericLength), MAX_SAFE_INTEGER);
+ }
+
+ /**
+ * Defines P on O based on the provided Desc.
+ *
+ * If P is "length", then its value for `writable`, if present, must
+ * be `true`—despite the fact that ハブ lengths are not writable.
+ * This is because the proxied value of `length` does not necessarily
+ * match that of the underlying object—any attempt to actually
+ * change this value, however, will fail.
+ *
+ * If P is a numeric index, then this function will return false
+ * if Desc defines a nonconfigurable, nonwritable, non·enumerable, or
+ * accessor property or if it is not a valid integer index for O.
+ */
+ defineProperty(O, P, Desc) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ if (
+ "get" in Desc || "set" in Desc || Desc.writable === false ||
+ Desc.value !== length
+ ) {
+ // An attempt to change the value or writability of `length`
+ // was made.
+ return false;
+ } else {
+ // The provided description for `length` does not attempt to
+ // change value or writability.
+ //
+ // This will still throw an error if `Desc.configurable` or
+ // `Desc.enumerable` is `true`, because this proxy wraps
+ // arrays.
+ return Reflect.defineProperty(
+ O,
+ P,
+ Object.fromEntries(
+ function* () {
+ if ("configurable" in Desc) {
+ yield ["configurable", Desc.configurable];
+ }
+ if ("enumerable" in Desc) {
+ yield ["enumerable", Desc.enumerable];
+ }
+ }(),
+ ),
+ );
+ }
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ if (numericIndex === undefined) {
+ // The provided property is not a numeric index.
+ return Reflect.definePropety(O, P, Desc);
+ } else if (isValidIntegerIndex.call({ length }, numericIndex)) {
+ // The provided property is a valid numeric index for the
+ // object.
+ if (
+ Desc.configurable === false || Desc.enumerable === false ||
+ "get" in Desc || "set" in Desc || Desc.writable === false
+ ) {
+ // An attempt to change immutable attributes of the index was
+ // made.
+ return false;
+ } else if (!("value" in Desc)) {
+ // The provided descriptor is compatible, but didn’t provide
+ // a value.
+ return true;
+ }
+ {
+ // The provided descriptor is compatible and provides a
+ // value, so the value can be set.
+ setItem.call(O, numericIndex, Desc.value);
+ return true;
+ }
+ } else {
+ // The provided property is a numeric index, but is not a valid
+ // integer index for the provided object.
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Deletes P from O.
+ *
+ * If P is "length", this function will return false.
+ *
+ * If P is a numeric index, this function will return false if it is
+ * a valid integer index for O and true otherwise.
+ */
+ deleteProperty(O, P) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ return false;
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ return numericIndex === undefined
+ ? Reflect.deleteProperty(O, P)
+ : !isValidIntegerIndex.call({ length }, numericIndex);
+ }
+ }
+
+ /**
+ * Gets P on O using the provided Receiver.
+ *
+ * "length" returns the length as a number, capped to
+ * `MAX_SAFE_INTEGER`.
+ *
+ * Valid integer indices return the item at that index. Other numeric
+ * indices return undefined.
+ */
+ get(O, P, Receiver) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ return length;
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ return numericIndex === undefined
+ ? Reflect.get(O, P, Receiver)
+ : isValidIntegerIndex.call({ length }, numericIndex)
+ ? getItem.call(O, numericIndex)
+ : undefined;
+ }
+ }
+
+ /**
+ * Gets a property descriptor for P on O.
+ *
+ * "length" returns a descriptor describing a nonconfigurable,
+ * non·enumerable, writable length, as a number capped to
+ * `MAX_SAFE_INTEGER`.
+ *
+ * Valid integer indices return a descriptor describing a
+ * configurable, enumerable, writable item at that index. Other
+ * numeric indices return undefined.
+ */
+ getOwnPropertyDescriptor(O, P) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ return {
+ configurable: false,
+ enumerable: false,
+ value: length,
+ writable: true,
+ };
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ return numericIndex === undefined
+ ? Reflect.getOwnPropertyDescriptor(O, P)
+ : isValidIntegerIndex.call({ length }, numericIndex)
+ ? {
+ configurable: true,
+ enumerable: true,
+ value: getItem.call(O, numericIndex),
+ writable: true,
+ }
+ : undefined;
+ }
+ }
+
+ /**
+ * Determines whether P exists on O .
+ *
+ * "length" always returns true.
+ *
+ * Valid integer indices return true. Other numeric indices return
+ * false.
+ */
+ has(O, P) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ return true;
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ return numericIndex === undefined
+ ? Reflect.has(O, P)
+ : isValidIntegerIndex.call({ length }, numericIndex);
+ }
+ }
+
+ /**
+ * Returns the own properties available on O .
+ *
+ * Valid integer indices are included.
+ */
+ ownKeys(O) {
+ const length = this.#length;
+ return [
+ ...function* () {
+ for (let i = 0; i < length; ++i) {
+ yield String(i);
+ }
+ },
+ ...function* () {
+ yield "length";
+ for (const P of Object.getOwnPropertyNames(O)) {
+ if (P == "length") {
+ // The current property name is "length".
+ /* do nothing */
+ } else {
+ const numericIndex = canonicalNumericIndexString(P);
+ if (
+ numericIndex === undefined ||
+ !(Object.is(numericIndex, 0) ||
+ numericIndex > 0 && numericIndex <= MAX_SAFE_INTEGER)
+ ) {
+ // The current property name is not "length" or an
+ // integer index. Note that there is no way to set or
+ // access numeric indices which are not integer indices,
+ // even though such a property would be listed here.
+ yield P;
+ } else {
+ // The current property name is an integer index. In
+ // practice, this will only be present if the object has
+ // been made non·extensible.
+ /* do nothing */
+ }
+ }
+ }
+ },
+ ...Object.getOwnPropertySymbols(O),
+ ];
+ }
+
+ /**
+ * Prevents extensions on O.
+ *
+ * Even though they won’t ever be accessed, proxy invariants mandate
+ * that indices for a nonextensible O exist as own properties, so
+ * they are defined here as configurable, writable, enumerable
+ * properties with a value of undefined.
+ */
+ preventExtensions(O) {
+ const length = this.#length;
+ if (Object.isExtensible(O)) {
+ // The provided object is currently extensible. Properties
+ // corresponding to its valid integer indices need to be defined
+ // on it.
+ for (let i = 0; i < length; ++i) {
+ Object.defineProperty(O, index, {
+ configurable: true,
+ enumerable: true,
+ value: undefined,
+ writable: true,
+ });
+ }
+ } else {
+ // The provided object is already not extensible.
+ /* do nothing */
+ }
+ return Reflect.preventExtensions(O);
+ }
+
+ /**
+ * Sets P on O to V using the provided Receiver.
+ *
+ * Attempting to set "length" will always fail silently.
+ *
+ * Valid integer indices set the item at that index. Other numeric
+ * indices fail silently.
+ */
+ set(O, P, V, Receiver) {
+ const length = this.#length;
+ if (P == "length") {
+ // The provided property is "length".
+ return true;
+ } else {
+ // The provided property is not "length".
+ const numericIndex = canonicalNumericIndexString(P);
+ if (numericIndex === undefined) {
+ // The provided propety is not a numeric index.
+ return Reflect.set(O, P, V, Receiver);
+ } else if (isValidIntegerIndex.call({ length }, numericIndex)) {
+ // The provided property is a valid integer index for the
+ // provided object.
+ setItem.call(O, numericIndex, V);
+ return true;
+ } else {
+ // The provided property in a numeric index, but not a valid
+ // integer index. This always fails silently.
+ return true;
+ }
+ }
+ }
+}
+
+/**
+ * Returns the array species, or `null` if no species was specified.
+ *
+ * If the provided value is not an array, this function always returns
+ * null.
+ */
+const arraySpecies = (originalArray) => {
+ if (!Array.isArray(originalArray)) {
+ return null;
+ } else {
+ const C = originalArray.constructor;
+ if (C === undefined || isObject(C)) {
+ const species = C?.[Symbol.species] ?? undefined;
+ if (species === undefined) {
+ return null;
+ } else if (!isConstructor(species)) {
+ throw new TypeError("ハブ: Species not constructable.");
+ } else {
+ return species;
+ }
+ } else {
+ throw new TypeError(
+ "ハブ: Constructor must be an object or undefined.",
+ );
+ }
+ }
+};
+
+/**
+ * Returns -0 if the provided argument is "-0"; returns a number
+ * representing the index if the provided argument is a canonical
+ * numeric index string; otherwise, returns undefined.
+ *
+ * There is no clamping of the numeric index, but note that numbers
+ * above 2^53 − 1 are not safe nor valid integer indices.
+ */
+const canonicalNumericIndexString = ($) => {
+ if (typeof $ != "string") {
+ return undefined;
+ } else if ($ === "-0") {
+ return -0;
+ } else {
+ const n = +$;
+ return $ === `${n}` ? n : undefined;
+ }
+};
+
+/**
+ * Defines a new array buffer on this which is the provided byte
+ * length.
+ */
+const defineNewBuffer = function defineNewBuffer(byteLength) {
+ Object.defineProperties(this, {
+ buffer: { ...unlisted, value: new ArrayBuffer(byteLength) },
+ byteLength: { ...unlisted, value: byteLength },
+ byteOffset: { ...unlisted, value: 0 },
+ });
+};
+
+/**
+ * Gets an item of the provided size and at the provided index from
+ * this buffer.
+ *
+ * The returned value will always be a big·int (not a number).
+ */
+const getItem = function getItem(index) {
+ const bitsPerItem = BigInt(validSize(this.bitWidth));
+ const bitIndex = BigInt(index);
+ const bytesPerElement = wordSizeByBits[bitsPerItem];
+ const wordSize = BigInt(bytesPerElement);
+ const typedArray = new typedArrayConstructors[bytesPerElement](
+ this.buffer,
+ this.byteOffset,
+ this.byteLength / bytesPerElement,
+ );
+ const scale = wordSize * 8n / bitsPerItem;
+ const offset = Number(bitIndex / scale);
+ if (offset >= typedArray.length) {
+ // The offset exceeds the length of the typed array. This case
+ // ought to be unreachable.
+ throw RangeError("ハブ: Index out of range.");
+ } else {
+ // The offset is within the bounds of the typed array.
+ const fill = (2n << (bitsPerItem - 1n)) - 1n;
+ const shift = bitsPerItem * (bitIndex % scale);
+ return BigInt(typedArray[offset]) >> shift & fill;
+ }
+};
+
+/** Returns whether the provided value is a constructor. */
+const isConstructor = (C) => {
+ if (!isObject(C)) {
+ // The provided value is not an object.
+ return false;
+ } else {
+ // The provided value is an object.
+ try {
+ Reflect.construct(
+ function () {},
+ [],
+ C,
+ ); // will throw if C is not a constructor
+ return true;
+ } catch {
+ return false;
+ }
+ }
+};
+
+/** Returns whether the provided value is an object. */
+const isObject = (O) => {
+ return O !== null &&
+ (typeof O == "function" || typeof O == "object");
+};
+
+/**
+ * Returns whether the provided number is a valid integer index for
+ * this object.
+ *
+ * Note that integer indices must be numbers, not big·ints, and the
+ * latter will throw an error.
+ */
+const isValidIntegerIndex = function isValidIntegerIndex($) {
+ return !(Object.is($, -0) || !Number.isInteger($) || $ < 0 ||
+ $ >= this.length);
+};
+
+/**
+ * Sets an item of the provided size and at the provided index to the
+ * provided value in this buffer.
+ *
+ * The value must be convertable to a big·int (not a number).
+ */
+const setItem = function setItem(index, value) {
+ const bitsPerItem = BigInt(validSize(this.bitWidth));
+ const bitIndex = BigInt(index);
+ const bytesPerElement = wordSizeByBits[bitsPerItem];
+ const wordSize = BigInt(bytesPerElement);
+ const typedArray = new typedArrayConstructors[bytesPerElement](
+ this.buffer,
+ this.byteOffset,
+ this.byteLength / bytesPerElement,
+ );
+ const scale = wordSize * 8n / bitsPerItem;
+ const offset = Number(bitIndex / scale);
+ if (offset >= typedArray.length) {
+ // The offset exceeds the length of the typed array. This case
+ // ought to be unreachable.
+ throw RangeError("ハブ: Index out of range.");
+ } else {
+ // The offset is within the bounds of the typed array.
+ const fill = (2n << (bitsPerItem - 1n)) - 1n;
+ const shift = bitsPerItem * (bitIndex % scale);
+ typedArray[offset] = (wordSize > 4 ? BigInt : Number)(
+ BigInt(typedArray[offset]) & ~(fill << shift) |
+ BigInt.asUintN(Number(bitsPerItem), value) << shift,
+ );
+ }
+};
+
+/**
+ * Converts the provided value to an array index, or throws an error if
+ * it is out of range.
+ */
+const toIndex = ($) => {
+ const integer = Math.floor($);
+ if (isNaN(integer) || integer == 0) {
+ // The value is zero·like.
+ return 0;
+ } else {
+ // The value is not zero·like.
+ const clamped = toLength(integer);
+ if (clamped !== integer) {
+ // Clamping the value changes it.
+ throw new RangeError(`ハブ: Index out of range: ${$}`);
+ } else {
+ // The value is within appropriate bounds.
+ return integer;
+ }
+ }
+};
+
+/**
+ * Converts the provided value to a length.
+ */
+const toLength = ($) => {
+ const len = Math.floor($);
+ return isNaN(len) || len == 0
+ ? 0
+ : Math.max(Math.min(len, MAX_SAFE_INTEGER), 0);
+};
+
+/** Maps bit widths to the corresponding typed array constructor. */
+const typedArrayConstructors = Object.assign(Object.create(null), {
+ 1: Uint8Array,
+ 2: Uint16Array,
+ 4: Uint32Array,
+ 8: BigUint64Array,
+});
+
+/**
+ * Definitions for non·enumerable nonconfigurable readonly properties.
+ */
+const unlisted = {
+ configurable: false,
+ enumerable: false,
+ writable: false,
+};
+
+/**
+ * Returns the provided argument as an integer if it is a valid bit
+ * width for a ハブ, and throws otherwise.
+ */
+const validSize = ($) => {
+ const n = +$;
+ if (!Number.isInteger(n) || n <= 0 || n > 64 || `${n}` != `${$}`) {
+ // The provided argument is not a valid bit width.
+ throw new TypeError(`ハブ: Invalid bit width: ${$}`);
+ } else {
+ // The provided argument is a valid bit width.
+ return n;
+ }
+};
+
+/**
+ * An array which maps sizes to the number of bytes which can fit them
+ * most compactly.
+ */
+const wordSizeByBits = [
+ ,
+ 1, // 1×8 (0 spares)
+ 1, // 2×4 (0 spares)
+ 2, // 3×5 (1 spare)
+ 1, // 4×2 (0 spares)
+ 2, // 5×3 (1 spare)
+ 4, // 6×5 (2 spares)
+ 8, // 7×9 (1 spare)
+ 1, // 8×1 (0 spares)
+ 8, // 9×7 (2 spares)
+ 4, // 10×3 (2 spares)
+ 2, // 11×1 (5 spares)
+ 2, // 12×1 (4 spares)
+ 2, // 13×1 (3 spares)
+ 2, // 14×1 (2 spares)
+ 2, // 15×1 (1 spare)
+ 2, // 16×1 (0 spares)
+ 8, // 17×3 (13 spares)
+ 8, // 18×3 (10 spares)
+ 8, // 19×3 (7 spares)
+ 8, // 20×3 (4 spares)
+ 8, // 21×3 (1 spare)
+ ...new Array(32 - 21).fill(4), // n×1 (32−n spares)
+ ...new Array(64 - 32).fill(8), // n×1 (64−n spares)
+];