From: Lady Date: Sun, 17 Apr 2022 02:04:45 +0000 (-0700) Subject: Initial commit X-Git-Tag: 0.1.0^0 X-Git-Url: https://git.ladys.computer/Habu/commitdiff_plain?ds=sidebyside Initial commit --- 5ec30d35142dd790fc90071bbba5750cd04c2322 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + 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 http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..aa207b7 --- /dev/null +++ b/README.markdown @@ -0,0 +1,31 @@ +# 🎐📦 ハブ + +A compact storage data structure for lists of bitfields with support +for arbitrary bitwidths (≤ 64). + +```js +import ハブ from "./mod.js"; + +const bitWidth = 5; +const length = 18; +const habu = new ハブ(bitWidth, length); +habu[1] = 0b11000n; +habu[17] = 0b01001n; + +habu.length; // 18 +habu.byteLength; // 12 +``` + +## Nomenclature + +ハブ is a Japanese word meaning “viper” or “hub”. +ハブクラゲ is the native name for +[Chironex yamaguchii][C. yamaguchii], a toxic box jellyfish. + +[C. yamaguchii]: + +## License + +Source files are licensed under the terms of the Mozilla Public +License, version 2.0. For more information, see +[LICENSE](./LICENSE). diff --git a/deno.json b/deno.json new file mode 100644 index 0000000..e5f93e5 --- /dev/null +++ b/deno.json @@ -0,0 +1,4 @@ +{ + "fmt": { "options": { "lineWidth": 71 } }, + "lint": { "rules": { "exclude": ["no-irregular-whitespace"] } } +} diff --git a/dev-deps.js b/dev-deps.js new file mode 100644 index 0000000..7f44831 --- /dev/null +++ b/dev-deps.js @@ -0,0 +1,12 @@ +// 🎐📦 ハブ ∷ dev-deps.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 . + +export { + assertStrictEquals, +} from "https://deno.land/std@0.134.0/testing/asserts.ts"; diff --git a/mod.js b/mod.js new file mode 100644 index 0000000..0ae42a6 --- /dev/null +++ b/mod.js @@ -0,0 +1,923 @@ +// 🎐📦 ハブ ∷ 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 . + +/** 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) +]; diff --git a/mod.test.js b/mod.test.js new file mode 100644 index 0000000..5a874f6 --- /dev/null +++ b/mod.test.js @@ -0,0 +1,189 @@ +// 🎐📦 ハブ ∷ mod.test.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 . + +import { assertStrictEquals } from "./dev-deps.js"; +import ハブ from "./mod.js"; + +Deno.test({ + name: "ハブ instances can store and retrieve data", + fn: () => { + for (let bitWidth = 1; bitWidth <= 64; ++bitWidth) { + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = new ハブ(bitWidth, 69); + assertStrictEquals(instance.length, 69); + assertStrictEquals( + instance.byteLength, + Math.ceil(69 / instance.wordScale) * instance.wordSize, + ); + for (const [index, value] of data.entries()) { + instance[index] = value; + } + for (const [index, value] of data.entries()) { + const actual = instance[index]; + assertStrictEquals( + actual, + value, + `Actual value for index ${index} of bitWidth ${bitWidth} was ${actual}, but ${value} was expected.`, + ); + } + } + }, +}); + +Deno.test({ + name: "ハブ instances can share buffers", + fn: () => { + const bitWidth = 7; + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = new ハブ(bitWidth, data); + const otherInstance = new ハブ(bitWidth, instance.buffer, 0, 69); + assertStrictEquals(otherInstance.length, 69); + for (const [index, value] of otherInstance.entries()) { + const actual = instance[index]; + assertStrictEquals( + actual, + value, + `Value mismatch for index ${index}.`, + ); + } + }, +}); + +Deno.test({ + name: "ハブ instances can subset other instances using array buffers", + fn: () => { + const bitWidth = 7; + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = new ハブ(bitWidth, data); + const otherInstance = new ハブ(bitWidth, instance.buffer, 8, 42); + assertStrictEquals(otherInstance.length, 42); + assertStrictEquals(otherInstance.byteLength, 40); + for (const [index, value] of otherInstance.entries()) { + const actual = instance[index + 9]; // 9 elements per 8 bytes + assertStrictEquals( + actual, + value, + `Value mismatch for index ${index}.`, + ); + } + }, +}); + +Deno.test({ + name: "ハブ.from", + fn: () => { + const bitWidth = 7; + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = ハブ.from(bitWidth, data); + for (const [index, value] of data.entries()) { + const actual = instance[index]; + assertStrictEquals( + actual, + value, + `Value mismatch for index ${index}.`, + ); + } + }, +}); + +Deno.test({ + name: "ハブ.of", + fn: () => { + const bitWidth = 7; + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = ハブ.of(bitWidth, ...data); + for (const [index, value] of data.entries()) { + const actual = instance[index]; + assertStrictEquals( + actual, + value, + `Value mismatch for index ${index}.`, + ); + } + }, +}); + +Deno.test({ + name: "ハブ#concat", + fn: () => { + const bitWidth = 7; + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield BigInt( + Math.random() * Number(1n << BigInt(bitWidth)) >>> 0, + ); + } + }()); + const instance = new ハブ(7); + const concatted = instance.concat(data); + assertStrictEquals(concatted.length, 69); + for (const [index, value] of data.entries()) { + const actual = concatted[index]; + assertStrictEquals(actual, value); + } + }, +}); + +Deno.test({ + name: "ハブ#constructor", + fn: () => { + const instance = new ハブ(7); + const { constructor } = instance; + assertStrictEquals(new constructor(5).bitWidth, 7); + assertStrictEquals(new constructor(5).length, 5); + assertStrictEquals(constructor[Symbol.species], constructor); + }, +}); + +Deno.test({ + name: "ハブ#filter", + fn: () => { + const data = Array.from(function* () { + for (let i = 0; i < 69; i++) { + yield i % 2 ? 0n : 1n; + } + }()); + const instance = new ハブ(7, data); + const filtered = instance.filter(($) => !!$); + assertStrictEquals(filtered.length, 35); + for (const value of filtered) { + assertStrictEquals(value, 1n); + } + }, +});