]> Lady’s Gitweb - Habu/blob - mod.js
Initial commit
[Habu] / mod.js
1 // 🎐📦 ハブ ∷ mod.js
2 // ====================================================================
3 //
4 // Copyright © 2022 Lady [@ Lady’s Computer].
5 //
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
9
10 /** 2^53 − 1. */
11 const MAX_SAFE_INTEGER = Number((1n << 53n) - 1n);
12
13 /**
14 * An object which can be built up in an arraylike fashion.
15 *
16 * This class copies the `from` and `of` static methods of Array to
17 * dodge Array limitations on `length`.
18 */
19 class MockArray extends Array {
20 /** Constructs a new MockArray as an ordinary (non·exotic) object. */
21 constuctor(...values) {
22 const array = Object.create(MockArray.prototype, {
23 length: {
24 configurable: false,
25 enumerable: false,
26 value: 0,
27 writable: true,
28 },
29 });
30 const numberOfArgs = values.length;
31 if (numberOfArgs == 0) {
32 // No arguments were supplied.
33 return array;
34 } else if (numberOfArgs == 1) {
35 // One argument was supplied.
36 const len = values[0];
37 if (typeof len != "number") {
38 // The argument was not a number.
39 return Object.assign(array, {
40 0: len,
41 length: 1,
42 });
43 } else {
44 // The argument was a number, and needs to be treated as a
45 // length.
46 const intLen = toLength(len); // allow larger length than Array
47 if (intLen != len) {
48 // The provided length was invalid.
49 throw new RangeError("ハブ: Invalid length.");
50 } else {
51 // The provided length was valid.
52 return Object.assign(array, { length: len });
53 }
54 }
55 } else {
56 // More than one argument was supplied.
57 return Object.assign(array, values, { length: numberOfArgs });
58 }
59 }
60 }
61
62 /**
63 * A generic container for lists of binary data of defined size.
64 *
65 * Values can be anywhere from 1 to 64 bits wide, although this class
66 * is not advantageous for widths larger than 21. Regardless of size,
67 * values will be represented as big·ints.
68 *
69 * This class trades computational efficiency getting and setting
70 * values for storage efficiency (ability to compact many values in a
71 * tight space); it is subsequently targeted at larger datasets which
72 * need to be available in memory but which don’t often need to be
73 * read.
74 *
75 * A note on limits: The upper limit for the length of an ordinary
76 * Ecmascript array of integers is 2^32 − 1. Each integer has 32 bytes
77 * which are readily accessible via bitwise operations, so that makes
78 * for 137 438 953 440 total bits accessible in an ordinary array.
79 * In contrast, an array buffer has a higher maximum byte length of
80 * 2^53 − 1, but obviously only allows for the storage of 8 bits per
81 * byte, for 72 057 594 037 927 928 total accessible bits. For
82 * technical reasons, the maximum total length of the ハブ instance is
83 * also capped to 2^53 − 1 (relevant for bit widths of less than 8).
84 *
85 * While this class uses an array buffer for its storage, and is
86 * conceptually more similar to Ecmascript typed arrays, it is an array
87 * exotic object and inherits from the ordinary Array class.
88 */
89 export default class ハブ extends Array {
90 /**
91 * Constructs a new ハブ with items of the provided size (in bits).
92 *
93 * The first argument must be the number of bits per item. If the
94 * second argument is an array buffer, it is used as the underlying
95 * store, and additional byte offset and length arguments may be
96 * supplied. Otherwise, if the second argument is an object, it is
97 * iterated over in a manner similar to `Array.from`. Otherwise, it
98 * is used as the length.
99 */
100 constructor(bitWidth, ...args) {
101 super(); // sets `length` (unused)
102 const bitsPerItem = validSize(bitWidth);
103 const wordSize = wordSizeByBits[bitsPerItem];
104 const scale = wordSize * 8 / bitsPerItem >> 0;
105 Object.defineProperties(
106 this,
107 {
108 wordScale: { ...unlisted, value: scale },
109 wordSize: { ...unlisted, value: wordSize },
110 bitWidth: { ...unlisted, value: bitsPerItem },
111 },
112 );
113 const length = (() => {
114 if (args.length == 0) {
115 // No additional arguments provided; initialize with zero
116 // length.
117 defineNewBuffer.call(this, 0);
118 return 0;
119 } else {
120 // An additional argument is present.
121 const firstArg = args[0];
122 const bufferByteLength = (() => {
123 try {
124 return Reflect.get(
125 ArrayBuffer.prototype,
126 "byteLength",
127 firstArg,
128 ); // will throw if not an array buffer
129 } catch {
130 return undefined;
131 }
132 })();
133 if (bufferByteLength != null) {
134 // The first additional argument is an array buffer.
135 const offset = toIndex(args[1]);
136 const length = args[2];
137 if (offset % wordSize || offset > bufferByteLength) {
138 // The provided offset exceeds the length of the buffer or is
139 // not divisible by the word size.
140 throw new RangeError("ハブ: Improper byte offset.");
141 } else if (length === undefined) {
142 // There is no provided length.
143 if (bufferByteLength % wordSize) {
144 // The provided buffer is not divisible by the word size.
145 throw new RangeError("ハブ: Improperly sized buffer.");
146 } else {
147 // The entire buffer after the offset should be used.
148 const newByteLength = bufferByteLength - offset;
149 const itemLength = BigInt(newByteLength / wordSize) *
150 BigInt(scale);
151 if (itemLength > MAX_SAFE_INTEGER) {
152 // If the entire buffer is used, it will result in a
153 // length greater than `MAX_SAFE_INTEGER`.
154 throw new RangeError("ハブ: Buffer too large.");
155 } else {
156 // The buffer is sized properly.
157 Object.defineProperties(this, {
158 buffer: { ...unlisted, value: firstArg },
159 byteLength: { ...unlisted, value: newByteLength },
160 byteOffset: { ...unlisted, value: offset },
161 });
162 return Number(itemLength);
163 }
164 }
165 } else {
166 // A length was provided.
167 const newByteLength = toIndex(Math.ceil(length / scale)) *
168 wordSize;
169 const itemLength = toIndex(length);
170 if (offset + newByteLength > bufferByteLength) {
171 // The resulting byte length combined with the offset
172 // exceeds the length of the buffer.
173 throw new RangeError("ハブ: Improper length.");
174 } else {
175 // All of the provided values check out and can be used.
176 Object.defineProperties(this, {
177 buffer: { ...unlisted, value: firstArg },
178 byteLength: { ...unlisted, value: newByteLength },
179 byteOffset: { ...unlisted, value: offset },
180 });
181 return itemLength;
182 }
183 }
184 } else if (
185 typeof firstArg == "function" ||
186 typeof firstArg == "object" && firstArg != null
187 ) {
188 // The first additional argument is an object, but not an
189 // array buffer.
190 const data = MockArray.from(firstArg);
191 const { length } = data;
192 defineNewBuffer.call(
193 this,
194 Math.ceil(length / scale) * wordSize,
195 );
196 for (const [index, datum] of data.entries()) {
197 setItem.call(this, index, datum);
198 }
199 return length;
200 } else {
201 // The first additional argument is a primitive.
202 const length = Math.floor(firstArg);
203 if (isNaN(length) || length == 0) {
204 // The provided argument is zero·like.
205 defineNewBuffer.call(this, 0);
206 return 0;
207 } else {
208 // The provided argument can’t be treated as zero.
209 const neededBytes = Math.ceil(length / scale) * wordSize;
210 if (neededBytes < 0 || neededBytes > MAX_SAFE_INTEGER) {
211 // The provided argument is not a valid length.
212 throw new RangeError(`ハブ: Invalid length: ${firstArg}`);
213 } else {
214 // The provided argument can be treated like a length.
215 defineNewBuffer.call(this, neededBytes);
216 return length;
217 }
218 }
219 }
220 }
221 })();
222 return new Proxy(this, new ハブ·ProxyHandler(length));
223 }
224
225 /**
226 * Returns a new ハブ instance of the provided bit width, generated
227 * in a manner akin to `Array.from()`.
228 */
229 static from(
230 bitWidth,
231 items,
232 mapFn = undefined,
233 thisArg = undefined,
234 ) {
235 return new (this ?? ハブ)(
236 bitWidth,
237 MockArray.from(items, mapFn, thisArg),
238 );
239 }
240
241 /** `isArray` should not be inherited, so is set to undefined. */
242 static isArray = undefined;
243
244 /**
245 * Returns a new ハブ instance of the provided bit width, generated
246 * in a manner akin to `Array.of()`.
247 */
248 static of(bitWidth, ...items) {
249 return new (this ?? ハブ)(bitWidth, MockArray.of(...items));
250 }
251
252 /**
253 * Returns a new ハブ instance of the provided bit width, generated
254 * in a manner akin to `Array.prototype.concat()`.
255 */
256 concat(...items) {
257 const Species = arraySpecies(this);
258 return Species == null ? [].concat(...items) : new Species(
259 Object.assign([], { constructor: MockArray }).concat(...items),
260 );
261 }
262
263 /**
264 * Returns the ハブ constructor, bound to the bit width of this ハブ
265 * instance.
266 */
267 //deno-lint-ignore adjacent-overload-signatures
268 get ["constructor"]() {
269 return ハブ.bind(undefined, this.bitWidth);
270 }
271
272 /** `copyWithin` should not be inherited, so is set to undefined. */
273 get copyWithin() {
274 return undefined;
275 }
276
277 /**
278 * Returns a new ハブ instance of the provided bit width, generated
279 * in a manner akin to `Array.prototype.filter()`.
280 */
281 filter(callbackfn, thisArg = undefined) {
282 const O = new Object(this);
283 const len = toLength(this.length);
284 if (typeof callbackfn != "function") {
285 // The callback is not callable.
286 throw new TypeError("ハブ: Callback must be callable.");
287 } else {
288 // The callback is callable.
289 const Species = arraySpecies(this);
290 const iterator = function* () {
291 for (let k = 0; k < len; ++k) {
292 if (k in O) {
293 // The current index is in the provided value.
294 const kValue = O[k];
295 if (callbackfn.call(thisArg, kValue, k, O)) {
296 // The callback returned true.
297 yield kValue;
298 } else {
299 // The callback returned false.
300 /* do nothing */
301 }
302 } else {
303 // The current index is not in the provided value.
304 /* do nothing */
305 }
306 }
307 }();
308 return Species == null
309 ? Array.from(iterator)
310 : new Species(iterator);
311 }
312 }
313
314 /** `flat` should not be inherited, so is set to undefined. */
315 get flat() {
316 return undefined;
317 }
318
319 /** `flatMap` should not be inherited, so is set to undefined. */
320 get flatMap() {
321 return undefined;
322 }
323
324 /** `pop` should not be inherited, so is set to undefined. */
325 get pop() {
326 return undefined;
327 }
328
329 /** `push` should not be inherited, so is set to undefined. */
330 get push() {
331 return undefined;
332 }
333
334 /** `shift` should not be inherited, so is set to undefined. */
335 get shift() {
336 return undefined;
337 }
338
339 /** `splice` should not be inherited, so is set to undefined. */
340 get splice() {
341 return undefined;
342 }
343
344 /** `unshift` should not be inherited, so is set to undefined. */
345 get unshift() {
346 return undefined;
347 }
348 }
349
350 /**
351 * A proxy handler for ハブ instances.
352 *
353 * Although ハブ instances are array exotic objects, this handler
354 * overrides the handling of both numeric indices and `length` so that
355 * the exotic array behaviour never actually takes place. Instead, data
356 * is pulled from the object’s associated buffer.
357 */
358 class ハブ·ProxyHandler extends Object.assign(
359 function () {},
360 { prototype: Reflect },
361 ) {
362 /**
363 * The actual number which should be returned as the length of the
364 * proxied value.
365 */
366 #length;
367
368 /**
369 * Constructs a new ハブ·ProxyHandler with the provided numeric
370 * length.
371 */
372 constructor(numericLength) {
373 super();
374 this.#length = Math.min(Number(numericLength), MAX_SAFE_INTEGER);
375 }
376
377 /**
378 * Defines P on O based on the provided Desc.
379 *
380 * If P is "length", then its value for `writable`, if present, must
381 * be `true`—despite the fact that ハブ lengths are not writable.
382 * This is because the proxied value of `length` does not necessarily
383 * match that of the underlying object—any attempt to actually
384 * change this value, however, will fail.
385 *
386 * If P is a numeric index, then this function will return false
387 * if Desc defines a nonconfigurable, nonwritable, non·enumerable, or
388 * accessor property or if it is not a valid integer index for O.
389 */
390 defineProperty(O, P, Desc) {
391 const length = this.#length;
392 if (P == "length") {
393 // The provided property is "length".
394 if (
395 "get" in Desc || "set" in Desc || Desc.writable === false ||
396 Desc.value !== length
397 ) {
398 // An attempt to change the value or writability of `length`
399 // was made.
400 return false;
401 } else {
402 // The provided description for `length` does not attempt to
403 // change value or writability.
404 //
405 // This will still throw an error if `Desc.configurable` or
406 // `Desc.enumerable` is `true`, because this proxy wraps
407 // arrays.
408 return Reflect.defineProperty(
409 O,
410 P,
411 Object.fromEntries(
412 function* () {
413 if ("configurable" in Desc) {
414 yield ["configurable", Desc.configurable];
415 }
416 if ("enumerable" in Desc) {
417 yield ["enumerable", Desc.enumerable];
418 }
419 }(),
420 ),
421 );
422 }
423 } else {
424 // The provided property is not "length".
425 const numericIndex = canonicalNumericIndexString(P);
426 if (numericIndex === undefined) {
427 // The provided property is not a numeric index.
428 return Reflect.definePropety(O, P, Desc);
429 } else if (isValidIntegerIndex.call({ length }, numericIndex)) {
430 // The provided property is a valid numeric index for the
431 // object.
432 if (
433 Desc.configurable === false || Desc.enumerable === false ||
434 "get" in Desc || "set" in Desc || Desc.writable === false
435 ) {
436 // An attempt to change immutable attributes of the index was
437 // made.
438 return false;
439 } else if (!("value" in Desc)) {
440 // The provided descriptor is compatible, but didn’t provide
441 // a value.
442 return true;
443 }
444 {
445 // The provided descriptor is compatible and provides a
446 // value, so the value can be set.
447 setItem.call(O, numericIndex, Desc.value);
448 return true;
449 }
450 } else {
451 // The provided property is a numeric index, but is not a valid
452 // integer index for the provided object.
453 return false;
454 }
455 }
456 }
457
458 /**
459 * Deletes P from O.
460 *
461 * If P is "length", this function will return false.
462 *
463 * If P is a numeric index, this function will return false if it is
464 * a valid integer index for O and true otherwise.
465 */
466 deleteProperty(O, P) {
467 const length = this.#length;
468 if (P == "length") {
469 // The provided property is "length".
470 return false;
471 } else {
472 // The provided property is not "length".
473 const numericIndex = canonicalNumericIndexString(P);
474 return numericIndex === undefined
475 ? Reflect.deleteProperty(O, P)
476 : !isValidIntegerIndex.call({ length }, numericIndex);
477 }
478 }
479
480 /**
481 * Gets P on O using the provided Receiver.
482 *
483 * "length" returns the length as a number, capped to
484 * `MAX_SAFE_INTEGER`.
485 *
486 * Valid integer indices return the item at that index. Other numeric
487 * indices return undefined.
488 */
489 get(O, P, Receiver) {
490 const length = this.#length;
491 if (P == "length") {
492 // The provided property is "length".
493 return length;
494 } else {
495 // The provided property is not "length".
496 const numericIndex = canonicalNumericIndexString(P);
497 return numericIndex === undefined
498 ? Reflect.get(O, P, Receiver)
499 : isValidIntegerIndex.call({ length }, numericIndex)
500 ? getItem.call(O, numericIndex)
501 : undefined;
502 }
503 }
504
505 /**
506 * Gets a property descriptor for P on O.
507 *
508 * "length" returns a descriptor describing a nonconfigurable,
509 * non·enumerable, writable length, as a number capped to
510 * `MAX_SAFE_INTEGER`.
511 *
512 * Valid integer indices return a descriptor describing a
513 * configurable, enumerable, writable item at that index. Other
514 * numeric indices return undefined.
515 */
516 getOwnPropertyDescriptor(O, P) {
517 const length = this.#length;
518 if (P == "length") {
519 // The provided property is "length".
520 return {
521 configurable: false,
522 enumerable: false,
523 value: length,
524 writable: true,
525 };
526 } else {
527 // The provided property is not "length".
528 const numericIndex = canonicalNumericIndexString(P);
529 return numericIndex === undefined
530 ? Reflect.getOwnPropertyDescriptor(O, P)
531 : isValidIntegerIndex.call({ length }, numericIndex)
532 ? {
533 configurable: true,
534 enumerable: true,
535 value: getItem.call(O, numericIndex),
536 writable: true,
537 }
538 : undefined;
539 }
540 }
541
542 /**
543 * Determines whether P exists on O .
544 *
545 * "length" always returns true.
546 *
547 * Valid integer indices return true. Other numeric indices return
548 * false.
549 */
550 has(O, P) {
551 const length = this.#length;
552 if (P == "length") {
553 // The provided property is "length".
554 return true;
555 } else {
556 // The provided property is not "length".
557 const numericIndex = canonicalNumericIndexString(P);
558 return numericIndex === undefined
559 ? Reflect.has(O, P)
560 : isValidIntegerIndex.call({ length }, numericIndex);
561 }
562 }
563
564 /**
565 * Returns the own properties available on O .
566 *
567 * Valid integer indices are included.
568 */
569 ownKeys(O) {
570 const length = this.#length;
571 return [
572 ...function* () {
573 for (let i = 0; i < length; ++i) {
574 yield String(i);
575 }
576 },
577 ...function* () {
578 yield "length";
579 for (const P of Object.getOwnPropertyNames(O)) {
580 if (P == "length") {
581 // The current property name is "length".
582 /* do nothing */
583 } else {
584 const numericIndex = canonicalNumericIndexString(P);
585 if (
586 numericIndex === undefined ||
587 !(Object.is(numericIndex, 0) ||
588 numericIndex > 0 && numericIndex <= MAX_SAFE_INTEGER)
589 ) {
590 // The current property name is not "length" or an
591 // integer index. Note that there is no way to set or
592 // access numeric indices which are not integer indices,
593 // even though such a property would be listed here.
594 yield P;
595 } else {
596 // The current property name is an integer index. In
597 // practice, this will only be present if the object has
598 // been made non·extensible.
599 /* do nothing */
600 }
601 }
602 }
603 },
604 ...Object.getOwnPropertySymbols(O),
605 ];
606 }
607
608 /**
609 * Prevents extensions on O.
610 *
611 * Even though they won’t ever be accessed, proxy invariants mandate
612 * that indices for a nonextensible O exist as own properties, so
613 * they are defined here as configurable, writable, enumerable
614 * properties with a value of undefined.
615 */
616 preventExtensions(O) {
617 const length = this.#length;
618 if (Object.isExtensible(O)) {
619 // The provided object is currently extensible. Properties
620 // corresponding to its valid integer indices need to be defined
621 // on it.
622 for (let i = 0; i < length; ++i) {
623 Object.defineProperty(O, index, {
624 configurable: true,
625 enumerable: true,
626 value: undefined,
627 writable: true,
628 });
629 }
630 } else {
631 // The provided object is already not extensible.
632 /* do nothing */
633 }
634 return Reflect.preventExtensions(O);
635 }
636
637 /**
638 * Sets P on O to V using the provided Receiver.
639 *
640 * Attempting to set "length" will always fail silently.
641 *
642 * Valid integer indices set the item at that index. Other numeric
643 * indices fail silently.
644 */
645 set(O, P, V, Receiver) {
646 const length = this.#length;
647 if (P == "length") {
648 // The provided property is "length".
649 return true;
650 } else {
651 // The provided property is not "length".
652 const numericIndex = canonicalNumericIndexString(P);
653 if (numericIndex === undefined) {
654 // The provided propety is not a numeric index.
655 return Reflect.set(O, P, V, Receiver);
656 } else if (isValidIntegerIndex.call({ length }, numericIndex)) {
657 // The provided property is a valid integer index for the
658 // provided object.
659 setItem.call(O, numericIndex, V);
660 return true;
661 } else {
662 // The provided property in a numeric index, but not a valid
663 // integer index. This always fails silently.
664 return true;
665 }
666 }
667 }
668 }
669
670 /**
671 * Returns the array species, or `null` if no species was specified.
672 *
673 * If the provided value is not an array, this function always returns
674 * null.
675 */
676 const arraySpecies = (originalArray) => {
677 if (!Array.isArray(originalArray)) {
678 return null;
679 } else {
680 const C = originalArray.constructor;
681 if (C === undefined || isObject(C)) {
682 const species = C?.[Symbol.species] ?? undefined;
683 if (species === undefined) {
684 return null;
685 } else if (!isConstructor(species)) {
686 throw new TypeError("ハブ: Species not constructable.");
687 } else {
688 return species;
689 }
690 } else {
691 throw new TypeError(
692 "ハブ: Constructor must be an object or undefined.",
693 );
694 }
695 }
696 };
697
698 /**
699 * Returns -0 if the provided argument is "-0"; returns a number
700 * representing the index if the provided argument is a canonical
701 * numeric index string; otherwise, returns undefined.
702 *
703 * There is no clamping of the numeric index, but note that numbers
704 * above 2^53 − 1 are not safe nor valid integer indices.
705 */
706 const canonicalNumericIndexString = ($) => {
707 if (typeof $ != "string") {
708 return undefined;
709 } else if ($ === "-0") {
710 return -0;
711 } else {
712 const n = +$;
713 return $ === `${n}` ? n : undefined;
714 }
715 };
716
717 /**
718 * Defines a new array buffer on this which is the provided byte
719 * length.
720 */
721 const defineNewBuffer = function defineNewBuffer(byteLength) {
722 Object.defineProperties(this, {
723 buffer: { ...unlisted, value: new ArrayBuffer(byteLength) },
724 byteLength: { ...unlisted, value: byteLength },
725 byteOffset: { ...unlisted, value: 0 },
726 });
727 };
728
729 /**
730 * Gets an item of the provided size and at the provided index from
731 * this buffer.
732 *
733 * The returned value will always be a big·int (not a number).
734 */
735 const getItem = function getItem(index) {
736 const bitsPerItem = BigInt(validSize(this.bitWidth));
737 const bitIndex = BigInt(index);
738 const bytesPerElement = wordSizeByBits[bitsPerItem];
739 const wordSize = BigInt(bytesPerElement);
740 const typedArray = new typedArrayConstructors[bytesPerElement](
741 this.buffer,
742 this.byteOffset,
743 this.byteLength / bytesPerElement,
744 );
745 const scale = wordSize * 8n / bitsPerItem;
746 const offset = Number(bitIndex / scale);
747 if (offset >= typedArray.length) {
748 // The offset exceeds the length of the typed array. This case
749 // ought to be unreachable.
750 throw RangeError("ハブ: Index out of range.");
751 } else {
752 // The offset is within the bounds of the typed array.
753 const fill = (2n << (bitsPerItem - 1n)) - 1n;
754 const shift = bitsPerItem * (bitIndex % scale);
755 return BigInt(typedArray[offset]) >> shift & fill;
756 }
757 };
758
759 /** Returns whether the provided value is a constructor. */
760 const isConstructor = (C) => {
761 if (!isObject(C)) {
762 // The provided value is not an object.
763 return false;
764 } else {
765 // The provided value is an object.
766 try {
767 Reflect.construct(
768 function () {},
769 [],
770 C,
771 ); // will throw if C is not a constructor
772 return true;
773 } catch {
774 return false;
775 }
776 }
777 };
778
779 /** Returns whether the provided value is an object. */
780 const isObject = (O) => {
781 return O !== null &&
782 (typeof O == "function" || typeof O == "object");
783 };
784
785 /**
786 * Returns whether the provided number is a valid integer index for
787 * this object.
788 *
789 * Note that integer indices must be numbers, not big·ints, and the
790 * latter will throw an error.
791 */
792 const isValidIntegerIndex = function isValidIntegerIndex($) {
793 return !(Object.is($, -0) || !Number.isInteger($) || $ < 0 ||
794 $ >= this.length);
795 };
796
797 /**
798 * Sets an item of the provided size and at the provided index to the
799 * provided value in this buffer.
800 *
801 * The value must be convertable to a big·int (not a number).
802 */
803 const setItem = function setItem(index, value) {
804 const bitsPerItem = BigInt(validSize(this.bitWidth));
805 const bitIndex = BigInt(index);
806 const bytesPerElement = wordSizeByBits[bitsPerItem];
807 const wordSize = BigInt(bytesPerElement);
808 const typedArray = new typedArrayConstructors[bytesPerElement](
809 this.buffer,
810 this.byteOffset,
811 this.byteLength / bytesPerElement,
812 );
813 const scale = wordSize * 8n / bitsPerItem;
814 const offset = Number(bitIndex / scale);
815 if (offset >= typedArray.length) {
816 // The offset exceeds the length of the typed array. This case
817 // ought to be unreachable.
818 throw RangeError("ハブ: Index out of range.");
819 } else {
820 // The offset is within the bounds of the typed array.
821 const fill = (2n << (bitsPerItem - 1n)) - 1n;
822 const shift = bitsPerItem * (bitIndex % scale);
823 typedArray[offset] = (wordSize > 4 ? BigInt : Number)(
824 BigInt(typedArray[offset]) & ~(fill << shift) |
825 BigInt.asUintN(Number(bitsPerItem), value) << shift,
826 );
827 }
828 };
829
830 /**
831 * Converts the provided value to an array index, or throws an error if
832 * it is out of range.
833 */
834 const toIndex = ($) => {
835 const integer = Math.floor($);
836 if (isNaN(integer) || integer == 0) {
837 // The value is zero·like.
838 return 0;
839 } else {
840 // The value is not zero·like.
841 const clamped = toLength(integer);
842 if (clamped !== integer) {
843 // Clamping the value changes it.
844 throw new RangeError(`ハブ: Index out of range: ${$}`);
845 } else {
846 // The value is within appropriate bounds.
847 return integer;
848 }
849 }
850 };
851
852 /**
853 * Converts the provided value to a length.
854 */
855 const toLength = ($) => {
856 const len = Math.floor($);
857 return isNaN(len) || len == 0
858 ? 0
859 : Math.max(Math.min(len, MAX_SAFE_INTEGER), 0);
860 };
861
862 /** Maps bit widths to the corresponding typed array constructor. */
863 const typedArrayConstructors = Object.assign(Object.create(null), {
864 1: Uint8Array,
865 2: Uint16Array,
866 4: Uint32Array,
867 8: BigUint64Array,
868 });
869
870 /**
871 * Definitions for non·enumerable nonconfigurable readonly properties.
872 */
873 const unlisted = {
874 configurable: false,
875 enumerable: false,
876 writable: false,
877 };
878
879 /**
880 * Returns the provided argument as an integer if it is a valid bit
881 * width for a ハブ, and throws otherwise.
882 */
883 const validSize = ($) => {
884 const n = +$;
885 if (!Number.isInteger(n) || n <= 0 || n > 64 || `${n}` != `${$}`) {
886 // The provided argument is not a valid bit width.
887 throw new TypeError(`ハブ: Invalid bit width: ${$}`);
888 } else {
889 // The provided argument is a valid bit width.
890 return n;
891 }
892 };
893
894 /**
895 * An array which maps sizes to the number of bytes which can fit them
896 * most compactly.
897 */
898 const wordSizeByBits = [
899 ,
900 1, // 1×8 (0 spares)
901 1, // 2×4 (0 spares)
902 2, // 3×5 (1 spare)
903 1, // 4×2 (0 spares)
904 2, // 5×3 (1 spare)
905 4, // 6×5 (2 spares)
906 8, // 7×9 (1 spare)
907 1, // 8×1 (0 spares)
908 8, // 9×7 (2 spares)
909 4, // 10×3 (2 spares)
910 2, // 11×1 (5 spares)
911 2, // 12×1 (4 spares)
912 2, // 13×1 (3 spares)
913 2, // 14×1 (2 spares)
914 2, // 15×1 (1 spare)
915 2, // 16×1 (0 spares)
916 8, // 17×3 (13 spares)
917 8, // 18×3 (10 spares)
918 8, // 19×3 (7 spares)
919 8, // 20×3 (4 spares)
920 8, // 21×3 (1 spare)
921 ...new Array(32 - 21).fill(4), // n×1 (32−n spares)
922 ...new Array(64 - 32).fill(8), // n×1 (64−n spares)
923 ];
This page took 0.29467 seconds and 5 git commands to generate.