From 9c6f304801adfdca48a32686aec8551338279863 Mon Sep 17 00:00:00 2001 From: mostafa elbannan Date: Fri, 8 Apr 2022 14:01:22 -0700 Subject: [PATCH 1/5] added some more debug tools for vec classes, and fixed typos/broken links in readme --- README.md | 61 ++++++++++++++++++----------- benchmarks/public/dist/compiler.js | 11 ++++-- benchmarks/public/dist/core.js | 2 + benchmarks/public/dist/index.js | 14 ++++--- buildInfo/index.js.br | Bin 4856 -> 4932 bytes codegenTests/codegen.test.ts | 8 ++++ codegenTests/default-js.mjs | 2 + codegenTests/default.ts | 2 + codegenTests/named-js.mjs | 2 + codegenTests/named.ts | 2 + dist-deno/compiler.ts | 13 ++++-- dist-deno/core.ts | 19 ++++++++- dist-deno/index.ts | 42 +++++++++++++++++--- dist-web/index.js | 42 ++++++++++---------- dist/compiler.d.ts | 1 + dist/compiler.d.ts.map | 2 +- dist/compiler.js | 14 +++++-- dist/core.d.ts | 18 +++++++++ dist/core.d.ts.map | 2 +- dist/core.js | 18 +++++++++ dist/index.d.ts | 27 ++++++++++++- dist/index.d.ts.map | 2 +- dist/index.js | 17 +++++--- package.json | 2 +- scripts/docgen.mjs | 4 +- src/compiler.ts | 14 +++++-- src/core.ts | 21 +++++++++- src/index.ts | 43 +++++++++++++++++--- src/tests/generation.test.ts | 20 ++++++++++ src/tests/naming.test.ts | 31 +++++++++++++++ 30 files changed, 369 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 0ed2584..71593b8 100644 --- a/README.md +++ b/README.md @@ -55,10 +55,10 @@ This package attempts to solve this problem by allowing you to define data struc - [Parallel Loop](#parallel-loop) - [Pushing Elements](#pushing-elements) - [API Reference](#api-reference) - - [Vec](#module_vec-struct.Vec) - - [validateStructDef](#module_vec-struct.validateStructDef) - - [vec](#module_vec-struct.vec_gen) - - [vecCompile](#module_vec-struct.vec_gencompile) + - [Vec](#module_vec-struct..Vec) + - [validateStructDef](#module_vec-struct..validateStructDef) + - [vec](#module_vec-struct..vec_gen) + - [vecCompile](#module_vec-struct..vec_gencompile) ## Examples @@ -528,7 +528,7 @@ If one sets a `f32` field with an incorrect type (`String` type for example), th #### i32 -A [32-bit signed integer](https://www.ibm.com/docs/en/aix/7.2?topic=types-signed-unsigned-integers), takes 4 bytes (32 bits) of memory. Similar to javascript's `Number` type, but without the ability to carry decimals. [`int` type](https://www.learnc.net/c-tutorial/c-integer/). +A [32-bit signed integer](https://www.ibm.com/docs/en/aix/7.2?topic=types-signed-unsigned-integers), takes 4 bytes (32 bits) of memory. Similar to javascript's `Number` type, but without the ability to carry decimals. Also similar to C's [`int` type](https://www.learnc.net/c-tutorial/c-integer/). To define a `i32` field: ```js @@ -991,14 +991,6 @@ Test machine was a Windows 11/WSL-Ubuntu 20.04 (x64), with a Intel i7-9750H CPU All of these tests are micro benchmarks which rarely tell the entire truth about performance, but can give you an idea on what to expect from vecs in terms of performance. -### Benchmarks Summary - -- [Iterating over a vec is nearly as fast as iterating over a buffer](#imperative-loop) -- [Vec iterators like `ForEach` are nearly as fast as imperative loops, in most javascript environments](#foreach-loop) -- [Vec ES6 iterators are really slow](#es6-iterator-loop) -- [Parallel iteration over vecs results in performance improvements you would expect from multithreading](#parallel-loop) -- [Preallocating memory before pushing many elements onto vec improves performance quite a bit](#pushing-elements) - ### Iteration #### Imperative loop @@ -1272,13 +1264,15 @@ Taken on ```March 31, 2022``` * [.swap(aIndex, bIndex)](#module_vec-struct..Vec+swap) ⇒ Vec.<StructDef> * [.toJSON()](#module_vec-struct..Vec+toJSON) ⇒ string * _static_ + * [.def](#module_vec-struct..Vec.def) : Readonly.<StructDef> + * [.elementSize](#module_vec-struct..Vec.elementSize) : Readonly.<number> * [.isVec(candidate)](#module_vec-struct..Vec.isVec) ⇒ boolean * [.fromMemory(memory)](#module_vec-struct..Vec.fromMemory) ⇒ Vec.<StructDef> * [.fromArray(structArray)](#module_vec-struct..Vec.fromArray) ⇒ Vec.<StructDef> * [.fromString(vecString)](#module_vec-struct..Vec.fromString) ⇒ Vec.<StructDef> * [~validateStructDef(def)](#module_vec-struct..validateStructDef) ⇒ boolean - * [~vec(structDef)](#module_vec-struct..vec) ⇒ VecClass.<StructDef> - * [~vecCompile(structDef, pathToLib, [options])](#module_vec-struct..vecCompile) ⇒ string + * [~vec(structDef, [options])](#module_vec-struct..vec_gen) ⇒ VecClass.<StructDef> + * [~vecCompile(structDef, pathToLib, [options])](#module_vec-struct..vec_genCompile) ⇒ string @@ -1346,6 +1340,8 @@ is type ```Vec``` * [.swap(aIndex, bIndex)](#module_vec-struct..Vec+swap) ⇒ Vec.<StructDef> * [.toJSON()](#module_vec-struct..Vec+toJSON) ⇒ string * _static_ + * [.def](#module_vec-struct..Vec.def) : Readonly.<StructDef> + * [.elementSize](#module_vec-struct..Vec.elementSize) : Readonly.<number> * [.isVec(candidate)](#module_vec-struct..Vec.isVec) ⇒ boolean * [.fromMemory(memory)](#module_vec-struct..Vec.fromMemory) ⇒ Vec.<StructDef> * [.fromArray(structArray)](#module_vec-struct..Vec.fromArray) ⇒ Vec.<StructDef> @@ -2638,6 +2634,25 @@ jsonVec.forEach(pos => { console.log(pos.e) // output: {x: 1, y: 1, z: 1} }) ``` + + +#### Vec.def : Readonly.<StructDef> +The definition of an individual +struct (element) in a vec class. + +**Kind**: static property of [Vec](#module_vec-struct..Vec) + + +#### Vec.elementSize : Readonly.<number> +The amount of raw memory an individual +struct (element of a vec) requires for vecs of this class. +An individual block of memory corresponds to +4 bytes (32-bits). + +For example if ```elementSize``` is 2, each struct +will take 8 bytes. + +**Kind**: static property of [Vec](#module_vec-struct..Vec) #### Vec.isVec(candidate) ⇒ boolean @@ -2820,9 +2835,9 @@ console.log(validateStructDef({x: {y: "f32"}})) // output: false console.log(validateStructDef({x: "f32"})) // output: true console.log(validateStructDef({code: "f32"})) // output: true ``` - + -### vec-struct~vec(structDef) ⇒ VecClass.<StructDef> +### vec-struct~vec(structDef, [options]) ⇒ VecClass.<StructDef> A vec compiler that can be used at runtime. Creates class definitions for growable array-like data structure (known as a vector or vec for short) that @@ -2846,9 +2861,11 @@ created, unlike normal arrays. **Returns**: VecClass.<StructDef> - A class that creates vecs which conform to inputted def -| Param | Type | Description | -| --- | --- | --- | -| structDef | StructDef | a type definition for the elements to be carried by an instance of the generated vec class | +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| structDef | StructDef | | a type definition for the elements to be carried by an instance of the generated vec class | +| [options] | Object | | | +| [options.className] | string | "AnonymousVec" | the value of the generated class's `name` property. Useful for debugging | **Example** *(Basic Usage)* ```js @@ -2866,7 +2883,7 @@ const geo = new geoCoordinates(15).fill({latitude: 1, longitude: 1}) const errClass = vec(null) // SyntaxError const errClass2 = vec({x: "unknownType"}) // SyntaxError ``` - + ### vec-struct~vecCompile(structDef, pathToLib, [options]) ⇒ string A vec compiler that can be used at build time. @@ -2900,7 +2917,7 @@ created, unlike normal arrays. | [options] | Object | | | | [options.bindings] | "js" \| "ts" | "js" | what language should vec class be generated in. Choose either "js" (javascript) or "ts" (typescript). Defaults to "js". | | [options.exportSyntax] | "none" \| "named" \| "default" | "none" | what es6 export syntax should class be generated with. Choose either "none" (no import statement with class), "named" (use the "export" syntax), or "default" (use "export default" syntax). Defaults to "none". | -| [options.className] | string | "\"AnonymousVec\"" | the name of the generated vec class. Defaults to "AnonymousVec". | +| [options.className] | string | "AnonymousVec" | the name of the generated vec class. Defaults to "AnonymousVec". | **Example** *(Basic Usage)* ```js diff --git a/benchmarks/public/dist/compiler.js b/benchmarks/public/dist/compiler.js index 1d8f404..6676608 100644 --- a/benchmarks/public/dist/compiler.js +++ b/benchmarks/public/dist/compiler.js @@ -184,6 +184,11 @@ function reservedJsKeyword(word) { return false; } } +export function invalidClassName(name) { + return (!validVariableName(name) + || reservedJsKeyword(name) + || name.length < 1); +} export function validateCompileOptions(input) { if (typeof input !== "object" || input === null @@ -195,9 +200,7 @@ export function validateCompileOptions(input) { throw TypeError("option 'pathToLib' missing"); } if (typeof input.className !== "string" - || !validVariableName(input.className) - || reservedJsKeyword(input.className) - || input.className.length < 1) { + || invalidClassName(input.className)) { throw SyntaxError(`inputted class name is not a valid javascript class name, got "${input.className}"`); } switch (input.exportSyntax) { @@ -236,6 +239,8 @@ ${ts || runtimeCompile * @extends {Vec${generic}} */`} ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? generic : ""} { + static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} ${ts ? "protected " : ""}static Cursor = class Cursor { _viewingIndex = 0${ts ? "\n\t\tself: Vec" + generic : ""} constructor(self${ts ? ": Vec" + generic : ""}) { this.self = self } diff --git a/benchmarks/public/dist/core.js b/benchmarks/public/dist/core.js index 16cf3b3..e4e170e 100644 --- a/benchmarks/public/dist/core.js +++ b/benchmarks/public/dist/core.js @@ -738,3 +738,5 @@ export class Vec { this._i32Memory = new Int32Array(memory.buffer); } } +Vec.def = {}; +Vec.elementSize = 0; diff --git a/benchmarks/public/dist/index.js b/benchmarks/public/dist/index.js index dd69807..a34ba02 100644 --- a/benchmarks/public/dist/index.js +++ b/benchmarks/public/dist/index.js @@ -1,5 +1,5 @@ import { Vec as BaseVec } from "./core.js"; -import { tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions } from "./compiler.js"; +import { tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions, invalidClassName } from "./compiler.js"; export { Vec } from "./core.js"; export function validateStructDef(def) { try { @@ -10,21 +10,25 @@ export function validateStructDef(def) { return false; } } -export function vec(structDef) { +export function vec(structDef, options = {}) { if (typeof SharedArrayBuffer === "undefined") { throw new Error(`${ERR_PREFIX} sharedArrayBuffers are not supported in this environment and are required for vecs`); } const tokens = tokenizeStructDef(structDef); - const { def, className } = createVecDef(tokens, structDef, { + const { className = "AnonymousVec" } = options; + if (invalidClassName(className)) { + throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${className}"`); + } + const { def, className: clsName } = createVecDef(tokens, structDef, { lang: "js", exportSyntax: "none", pathToLib: "none", - className: "AnonymousVec", + className, runtimeCompile: true }); const genericVec = Function(`"use strict";return (Vec) => { ${def} - return ${className} + return ${clsName} }`)()(BaseVec); return genericVec; } diff --git a/buildInfo/index.js.br b/buildInfo/index.js.br index 3407c670c21b05220353038f6564b23080e5d5c3..94791f265fe0029390d6e6c35cfa35efa0fed39f 100644 GIT binary patch literal 4932 zcmV-K6T9pi`$ZAetN{ejQ5ZKqA3@o@*4kFAvBeem|Lakny5?`B$cFfvYE~|`Mgw}7$ycfeh%uGQ;abc*Dqg9zkVUwNwCBt zQaTn-Olg0uaX3DCvO4n`Jpx^&{r_#6pYUi5A#Q;??9v&NvW@P&@4n-iktUk)$S0C) zC0aS)Y{=^ce(wo(G_u#Qq#!83(3EL<;}R=osqUL z;n$I+X{SFU*}3VfLF&;p%Wz?jqYdkd}`WZ!qoQ1{mOwW{z8ao{$z0rX(&BT z92o=yQLC=Oh zR5h0?qLQeJ457$MQc7tTe~)~RKyukGX{S7v^b*t?f}BEEG$1WQT+clGwG&M@qWmZ3 z;VG`2LaugMm7*^I3<@{lf*x=gRhm1omt5z%9Qmv~FBn?yL_!?!1#V zPl;bc6ot!kEzKbZwO8e=Rcnkyh#4nZf)g{$_{q!glWMgW>%vM%@xy%RzzOptym8t5$@s^BJJrGqvIHvPja6&HxIG>g*N^@k?g9=RFie{B@(zg#5t5!6hMpOcg8Ve>leGQT+M?Ln%cUQ8lGOYLUm{cr8W+VYZLrc~WpNj=SUKNoqT- zdL0))1reVB8D}Yj_mwjxKA$@wq~JwWGg79gGo`t{Jz0WT(`);(1d(L?HoHXJJ&Z+` ziUN~*Bb0%}lw2g0RazjUECF-08UaEk#e3mG=}oD=!M%>5zXQL2y!M8Il1!i}MbB5C zYWlrY5bFZ+ro!s2DMYpWUa(N00%@pv0S$Ql--VEcTV{2hkM2*|h0`n^qT2q4|GME@ z-0s~>i*RXmRh%jL?%D*~!~HEfn;GEM^4Z$O$Ew$I5yTF0^_C0R^sAd?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Wcl{wEVv+khHgaS1qUdJ19(085dW@^ zBzM}D89%3JdZZyAp4L%tNUyfok z864`;J2|;EH0;gp#w9;IHu0YgHOib60}@#5fhlk*H+?9sh{54&CDLFXGr zKz>zQN_@Y-PAAB6=Gl4AuSJ3Y5)c6(nlT)(lGlM3rOaFRZIJL-TZu!7X(a}% ze_CQedn3`p6Uf8WqFO3Kx3Sl#va(}VX;KfQ$HCnE{$w-B0t+@Xb|o&pr6Zeuu$WS< zF~88d5`RMrFE&E!AMK6;M&<3z{PzY57=FhGSKPSipx&83NVhg(2s>@~Hq8H(5~swN zhxDen;P(c$+~FQ0i{I>2$~UVAlTjM818;G+FhL;NqNRvC1gq&eN1WHGwF7sG({lMI zPDh@o7W3wblr<*Y_{WO^{oB8rrk)WKwX(e2f@Rp0^n$l{PZgAKMMa;`Qp%bbZ(vnI zmLj^sYFYsVkulCR%8uY$003c%E~d3fX^WhSL5c|qqE+#e-bQbOgg(5sYAr1>z)28B zsyEBEv~86T5edN9qxcdI90eMp8i<<1oj5t|+$h#-3+9=EUkF2Du~iTiWRWcain$ zJ{}oS{73>rF~Dvfz0`BhSW#MA!|H4xWW>nh1{?zoJJIBs&+_AKpIra6w!R<49BDuG zqOL_+VLMyZsqcln54fQSpL-7Bj zppxpSM?f^q+a%UIZ9hgF8yT6wQe(3HWR`_j61~)T@F~*`VK9Yl62QTANuK3IB_DuLk2gM^Eomti+yA4Ng z9b>W#xw~YdGAZ}#< diff --git a/codegenTests/codegen.test.ts b/codegenTests/codegen.test.ts index da4b896..a9810d2 100644 --- a/codegenTests/codegen.test.ts +++ b/codegenTests/codegen.test.ts @@ -13,6 +13,8 @@ describe("generated vec classes have all the standard methods and properties", ( expect(typeof NamedTs.fromMemory).toBe("function") expect(typeof NamedTs.fromString).toBe("function") expect(typeof NamedTs.isVec).toBe("function") + expect(NamedTs.def).toEqual(structdef) + expect(NamedTs.elementSize).toBe(3) const v = new NamedTs(15).fill({ x: true, y: 10, z: "a" }) @@ -69,6 +71,8 @@ describe("generated vec classes have all the standard methods and properties", ( expect(typeof NamedJs.fromMemory).toBe("function") expect(typeof NamedJs.fromString).toBe("function") expect(typeof NamedJs.isVec).toBe("function") + expect(NamedJs.def).toEqual(structdef) + expect(NamedJs.elementSize).toBe(3) const v = new NamedJs(15).fill({ x: true, y: 10, z: "a" }) @@ -125,6 +129,8 @@ describe("generated vec classes have all the standard methods and properties", ( expect(typeof defaultTs.DefaultTs.fromMemory).toBe("function") expect(typeof defaultTs.DefaultTs.fromString).toBe("function") expect(typeof defaultTs.DefaultTs.isVec).toBe("function") + expect(defaultTs.DefaultTs.def).toEqual(structdef) + expect(defaultTs.DefaultTs.elementSize).toBe(3) const v = new defaultTs.DefaultTs(15).fill({ x: true, y: 10, z: "a" }) @@ -181,6 +187,8 @@ describe("generated vec classes have all the standard methods and properties", ( expect(typeof defaultJs.DefaultJs.fromMemory).toBe("function") expect(typeof defaultJs.DefaultJs.fromString).toBe("function") expect(typeof defaultJs.DefaultJs.isVec).toBe("function") + expect(defaultJs.DefaultJs.def).toEqual(structdef) + expect(defaultJs.DefaultJs.elementSize).toBe(3) const v = new defaultJs.DefaultJs(15).fill({ x: true, y: 10, z: "a" }) diff --git a/codegenTests/default-js.mjs b/codegenTests/default-js.mjs index cbbe277..55ae317 100644 --- a/codegenTests/default-js.mjs +++ b/codegenTests/default-js.mjs @@ -3,6 +3,8 @@ import {Vec} from "../dist" * @extends {Vec<{"x":"bool","y":"f32","z":"char"}>} */ class DefaultJs extends Vec { + static def = {"x":"bool","y":"f32","z":"char"} + static elementSize = 3 static Cursor = class Cursor { _viewingIndex = 0 constructor(self) { this.self = self } diff --git a/codegenTests/default.ts b/codegenTests/default.ts index 437247a..7fc39e5 100644 --- a/codegenTests/default.ts +++ b/codegenTests/default.ts @@ -1,6 +1,8 @@ import {Vec, StructDef, Struct, CursorConstructor} from "../dist" class DefaultTs extends Vec<{"x":"bool","y":"f32","z":"char"}> { + static readonly def : StructDef = {"x":"bool","y":"f32","z":"char"} + static readonly elementSize : number = 3 protected static Cursor = class Cursor { _viewingIndex = 0 self: Vec<{"x":"bool","y":"f32","z":"char"}> diff --git a/codegenTests/named-js.mjs b/codegenTests/named-js.mjs index 3b87b99..11fa9bf 100644 --- a/codegenTests/named-js.mjs +++ b/codegenTests/named-js.mjs @@ -3,6 +3,8 @@ import {Vec} from "../dist" * @extends {Vec<{"x":"bool","y":"f32","z":"char"}>} */ export class NamedJs extends Vec { + static def = {"x":"bool","y":"f32","z":"char"} + static elementSize = 3 static Cursor = class Cursor { _viewingIndex = 0 constructor(self) { this.self = self } diff --git a/codegenTests/named.ts b/codegenTests/named.ts index f778283..491f132 100644 --- a/codegenTests/named.ts +++ b/codegenTests/named.ts @@ -1,6 +1,8 @@ import {Vec, StructDef, Struct, CursorConstructor} from "../dist" export class NamedTs extends Vec<{"x":"bool","y":"f32","z":"char"}> { + static readonly def : StructDef = {"x":"bool","y":"f32","z":"char"} + static readonly elementSize : number = 3 protected static Cursor = class Cursor { _viewingIndex = 0 self: Vec<{"x":"bool","y":"f32","z":"char"}> diff --git a/dist-deno/compiler.ts b/dist-deno/compiler.ts index 5122903..c5934ab 100644 --- a/dist-deno/compiler.ts +++ b/dist-deno/compiler.ts @@ -196,6 +196,13 @@ function reservedJsKeyword(word: string): boolean { return false } } +export function invalidClassName(name: string): boolean { + return ( + !validVariableName(name) + || reservedJsKeyword(name) + || name.length < 1 + ) +} export function validateCompileOptions(input: any) { if ( typeof input !== "object" @@ -212,9 +219,7 @@ export function validateCompileOptions(input: any) { } if ( typeof input.className !== "string" - || !validVariableName(input.className) - || reservedJsKeyword(input.className) - || input.className.length < 1 + || invalidClassName(input.className) ) { throw SyntaxError(`inputted class name is not a valid javascript class name, got "${input.className}"`) } @@ -279,6 +284,8 @@ ${ts || runtimeCompile ${ exportSyntax === "named" ? "export " : "" }class ${className} extends Vec${ts ? generic : ""} { + static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} ${ts ? "protected " : ""}static Cursor = class Cursor { _viewingIndex = 0${ ts ? "\n\t\tself: Vec" + generic : "" diff --git a/dist-deno/core.ts b/dist-deno/core.ts index 242e18c..0fd4d3b 100644 --- a/dist-deno/core.ts +++ b/dist-deno/core.ts @@ -45,7 +45,24 @@ export const VALID_DATA_TYPES_INTERNAL = [ * is type ```Vec``` */ export class Vec { - + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {Readonly} + */ + static readonly def: StructDef = {} + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {Readonly} + */ + static readonly elementSize: number = 0 /** * Checks if input is a of Vec type. * diff --git a/dist-deno/index.ts b/dist-deno/index.ts index fc10927..7831e5d 100644 --- a/dist-deno/index.ts +++ b/dist-deno/index.ts @@ -3,7 +3,7 @@ */ import {Vec as BaseVec} from "./core.ts" import type {StructDef, Struct, ReadonlyInt32Array} from "./core.ts" -import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions} from "./compiler.ts" +import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions, invalidClassName} from "./compiler.ts" export {Vec} from "./core.ts" export type {CursorConstructor, VecCursor, ReadonlyInt32Array, } from "./core.ts" export type {SortCompareCallback, MapCallback} from "./core.ts" @@ -66,6 +66,9 @@ export function validateStructDef(def: any): boolean { * @param {StructDef} structDef a type definition for the elements * to be carried by an instance of the generated vec * class + * @param {Object} [options] + * @param {string} [options.className=AnonymousVec] the value + * of the generated class's `name` property. Useful for debugging * @returns {VecClass} A class that creates vecs which conform * to inputted def * @@ -87,22 +90,31 @@ export function validateStructDef(def: any): boolean { * ``` */ export function vec( - structDef: S + structDef: S, + options: { + className?: string + } = {} ): VecClass { if (typeof SharedArrayBuffer === "undefined") { throw new Error(`${ERR_PREFIX} sharedArrayBuffers are not supported in this environment and are required for vecs`) } const tokens = tokenizeStructDef(structDef) - const {def, className} = createVecDef(tokens, structDef, { + const { + className = "AnonymousVec" + } = options + if (invalidClassName(className)) { + throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${className}"`) + } + const {def, className: clsName} = createVecDef(tokens, structDef, { lang: "js", exportSyntax: "none", pathToLib: "none", - className: "AnonymousVec", + className, runtimeCompile: true }) const genericVec = Function(`"use strict";return (Vec) => { ${def} - return ${className} + return ${clsName} }`)()(BaseVec) return genericVec } @@ -143,7 +155,7 @@ export function vec( * "none" (no import statement with class), "named" (use * the "export" syntax), or "default" (use "export default" * syntax). Defaults to "none". - * @param {string} [options.className="AnonymousVec"] the name of the generated + * @param {string} [options.className=AnonymousVec] the name of the generated * vec class. Defaults to "AnonymousVec". * @returns {string} a string rendition of vec class * @@ -202,6 +214,24 @@ export function vecCompile( return def } export interface VecClass { + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {StructDef} + */ + readonly def: StructDef + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {number} + */ + readonly elementSize: number /** * Checks if input is a of Vec type. * diff --git a/dist-web/index.js b/dist-web/index.js index 60488fd..afed7e3 100644 --- a/dist-web/index.js +++ b/dist-web/index.js @@ -1,31 +1,33 @@ -var structVec=(()=>{var T=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var X=(h,e)=>{for(var t in e)T(h,t,{get:e[t],enumerable:!0})},Z=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of G(e))!U.call(h,s)&&s!==t&&T(h,s,{get:()=>e[s],enumerable:!(n=q(e,s))||n.enumerable});return h};var H=h=>Z(T({},"__esModule",{value:!0}),h);var se={};X(se,{Vec:()=>M,default:()=>ne,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>D});var E=Float32Array,N=SharedArrayBuffer,k=["f32","i32","char","bool"],M=class{constructor(e=15,t){try{let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this)}catch(n){throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${n}`)}}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,f=r*n;return l.copyWithin(0,a,f),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){try{let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=E.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new E(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}catch(t){throw console.error("Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation",t),t}}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,f=c*s,g=s,y=a+g,u=y;for(this._length=o;us)try{let o=s*2,c=i>o?i+15:o,l=E.BYTES_PER_ELEMENT*t*c,a=8+l,f=new N(a),g=new E(f);g.set(this._f32Memory),this.replaceMemory(g),this._capacity=c}catch(o){throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${o}`)}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let f=r;fn.length){let f=r+n.length;for(let x=r;x=s?this:(this._f32Memory=this.shrinkCapacity(r),this._capacity=r,this)}catch(t){throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${t}`)}}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${v} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${u?", StructDef, Struct, CursorConstructor":""}} from ${x}`,L="CursorConstructor"+d,O=u?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=u?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` +var structVec=(()=>{var T=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)T(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&T(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(T({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>B,vec:()=>D,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,k=["f32","i32","char","bool"],v=class{constructor(e=15,t){try{let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this)}catch(n){throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${n}`)}}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,u=r*n;return l.copyWithin(0,a,u),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){try{let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}catch(t){throw console.error("Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation",t),t}}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,u=c*s,m=s,y=a+m,f=y;for(this._length=o;fs)try{let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,u=new N(a),m=new M(u);m.set(this._f32Memory),this.replaceMemory(m),this._capacity=c}catch(o){throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${o}`)}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let u=r;un.length){let u=r+n.length;for(let x=r;x=s?this:(this._f32Memory=this.shrinkCapacity(r),this._capacity=r,this)}catch(t){throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${t}`)}}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${f?", StructDef, Struct, CursorConstructor":""}} from ${x}`,L="CursorConstructor"+d,P=f?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=f?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` ${n!=="none"?z:""} -${u||r?"":`/** +${f||r?"":`/** * @extends {Vec${d}} */`} -${i==="named"?"export ":""}class ${s} extends Vec${u?d:""} { - ${u?"protected ":""}static Cursor = class Cursor { - _viewingIndex = 0${u?` +${i==="named"?"export ":""}class ${s} extends Vec${f?d:""} { + static ${f?"readonly ":""}def ${f?": StructDef":""} = ${y} + static ${f?"readonly ":""}elementSize ${f?": number":""} = ${o} + ${f?"protected ":""}static Cursor = class Cursor { + _viewingIndex = 0${f?` self: Vec`+d:""} - constructor(self${u?": Vec"+d:""}) { this.self = self } - ${l.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${O}[this._viewingIndex${$}]`,p=u?": number":"",I=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${I}; ${S};`}).join(` + constructor(self${f?": Vec"+d:""}) { this.self = self } + ${l.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${P}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${g}()${p} { return ${w} }`,S=`set ${g}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${g.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=u?": number":"",I=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${I}; ${S};`}).join(` + ${m.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${g}()${p} { return ${w} }`,S=`set ${g}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${f.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=u?": string":"",I=`get ${m}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${m}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${I}; ${S};`}).join(` + ${u.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": string":"",E=`get ${g}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${g}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${E}; ${S};`}).join(` `)} - ${a.map(({field:m,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,I=~p,S=u?": boolean":"",P=u?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",A=`${V}[this._viewingIndex${w}]`,Y=`get ${m}()${S} { return Boolean(${A} & ${p}) }`,J=`set ${m}(newValue${S}) { ${A} &= ${I};${A} |= ${P}${$<1?"":" << "+$.toString()}}`;return`${Y}; ${J};`}).join(` + ${a.map(({field:g,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,E=~p,S=f?": boolean":"",Y=f?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",A=`${V}[this._viewingIndex${w}]`,J=`get ${g}()${S} { return Boolean(${A} & ${p}) }`,q=`set ${g}(newValue${S}) { ${A} &= ${E};${A} |= ${Y}${$<1?"":" << "+$.toString()}}`;return`${J}; ${q};`}).join(` `)} - set e({${c.map(m=>m).join(", ")}}${u?": Struct"+d:""}) { ${c.map(m=>"this."+m+" = "+m).join(";")}; } - get e()${u?": Struct"+d:""} { return {${c.map(m=>m+": this."+m).join(", ")}} } - }${u?" as "+L:""} - get elementSize()${u?": number":""} { return ${o} } - get def()${u?": StructDef":""} { return ${y} } - ${u?"protected ":""}get cursorDef()${u?": "+L:""} { return ${s}.Cursor } + set e({${c.map(g=>g).join(", ")}}${f?": Struct"+d:""}) { ${c.map(g=>"this."+g+" = "+g).join(";")}; } + get e()${f?": Struct"+d:""} { return {${c.map(g=>g+": this."+g).join(", ")}} } + }${f?" as "+L:""} + get elementSize()${f?": number":""} { return ${o} } + get def()${f?": StructDef":""} { return ${y} } + ${f?"protected ":""}get cursorDef()${f?": "+L:""} { return ${s}.Cursor } } ${i==="default"?`export default {${s}}`:""} -`.trim()}}function j(h){try{return b(h),!0}catch(e){return!1}}function B(h){if(typeof SharedArrayBuffer=="undefined")throw new Error(`${v} sharedArrayBuffers are not supported in this environment and are required for vecs`);let e=b(h),{def:t,className:n}=W(e,h,{lang:"js",exportSyntax:"none",pathToLib:"none",className:"AnonymousVec",runtimeCompile:!0});return Function(`"use strict";return (Vec) => { - ${t} - return ${n} - }`)()(M)}function D(h,e,t={}){let{lang:n="js",exportSyntax:s="none",className:i="AnonymousVec"}=t,r={lang:n,pathToLib:e,className:i,exportSyntax:s,runtimeCompile:!1};C(r);let o=b(h),{def:c}=W(o,h,r);return c}var ne={vec:B,Vec:M,validateStructDef:j,vecCompile:D};return H(se);})(); +`.trim()}}function B(h){try{return b(h),!0}catch(e){return!1}}function D(h,e={}){if(typeof SharedArrayBuffer=="undefined")throw new Error(`${I} sharedArrayBuffers are not supported in this environment and are required for vecs`);let t=b(h),{className:n="AnonymousVec"}=e;if(W(n))throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${n}"`);let{def:s,className:i}=C(t,h,{lang:"js",exportSyntax:"none",pathToLib:"none",className:n,runtimeCompile:!0});return Function(`"use strict";return (Vec) => { + ${s} + return ${i} + }`)()(v)}function O(h,e,t={}){let{lang:n="js",exportSyntax:s="none",className:i="AnonymousVec"}=t,r={lang:n,pathToLib:e,className:i,exportSyntax:s,runtimeCompile:!1};j(r);let o=b(h),{def:c}=C(o,h,r);return c}var se={vec:D,Vec:v,validateStructDef:B,vecCompile:O};return K(ie);})(); diff --git a/dist/compiler.d.ts b/dist/compiler.d.ts index cc3fb42..82c2d7f 100644 --- a/dist/compiler.d.ts +++ b/dist/compiler.d.ts @@ -22,6 +22,7 @@ declare type StructDefToken = { }[]; }; export declare function tokenizeStructDef(def: any): StructDefToken; +export declare function invalidClassName(name: string): boolean; export declare function validateCompileOptions(input: any): void; declare type DefOptions = { lang: "js" | "ts"; diff --git a/dist/compiler.d.ts.map b/dist/compiler.d.ts.map index ec897f4..800209a 100644 --- a/dist/compiler.d.ts.map +++ b/dist/compiler.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"compiler.d.ts","sourceRoot":"","sources":["../src/compiler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAsC,MAAM,QAAQ,CAAA;AAKrE,eAAO,MAAM,UAAU,mBAAmB,CAAA;AAM1C,aAAK,cAAc,GAAG;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,aAAa,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;IAChD,WAAW,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;IAC9C,aAAa,EAAE;QACX,KAAK,EAAE,MAAM,CAAA;QACb,MAAM,EAAE,MAAM,CAAA;QACd,UAAU,EAAE,MAAM,CAAA;KACrB,EAAE,CAAC;IACJ,UAAU,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;CAChD,CAAA;AA6BD,wBAAgB,iBAAiB,CAAC,GAAG,E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AgB,iBAAiB,CAAC,GAAG,EAAE,GAAG,GAAG,cAAc,CA8G1D;AAuDD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMtD;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,GAAG,QAkChD;AAED,aAAK,UAAU,GAAG;IACd,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAA;IAC1C,cAAc,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED,wBAAgB,YAAY,CACxB,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,SAAS,EACpB,EACI,IAAI,EACJ,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACjB,EAAE,UAAU,GACd;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAC,CAqGlC"} \ No newline at end of file diff --git a/dist/compiler.js b/dist/compiler.js index 2f02614..06908d1 100644 --- a/dist/compiler.js +++ b/dist/compiler.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.createVecDef = exports.validateCompileOptions = exports.tokenizeStructDef = exports.ERR_PREFIX = void 0; +exports.createVecDef = exports.validateCompileOptions = exports.invalidClassName = exports.tokenizeStructDef = exports.ERR_PREFIX = void 0; const core_1 = require("./core"); // Allows for alpha-numeric characters, $, and _. // Numbers are not allow to be the first character. @@ -190,6 +190,12 @@ function reservedJsKeyword(word) { return false; } } +function invalidClassName(name) { + return (!validVariableName(name) + || reservedJsKeyword(name) + || name.length < 1); +} +exports.invalidClassName = invalidClassName; function validateCompileOptions(input) { if (typeof input !== "object" || input === null @@ -201,9 +207,7 @@ function validateCompileOptions(input) { throw TypeError("option 'pathToLib' missing"); } if (typeof input.className !== "string" - || !validVariableName(input.className) - || reservedJsKeyword(input.className) - || input.className.length < 1) { + || invalidClassName(input.className)) { throw SyntaxError(`inputted class name is not a valid javascript class name, got "${input.className}"`); } switch (input.exportSyntax) { @@ -243,6 +247,8 @@ ${ts || runtimeCompile * @extends {Vec${generic}} */`} ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? generic : ""} { + static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} ${ts ? "protected " : ""}static Cursor = class Cursor { _viewingIndex = 0${ts ? "\n\t\tself: Vec" + generic : ""} constructor(self${ts ? ": Vec" + generic : ""}) { this.self = self } diff --git a/dist/core.d.ts b/dist/core.d.ts index 1e52b8f..25c686c 100644 --- a/dist/core.d.ts +++ b/dist/core.d.ts @@ -29,6 +29,24 @@ export declare const VALID_DATA_TYPES_INTERNAL: readonly ["f32", "i32", "char", * is type ```Vec``` */ export declare class Vec { + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {Readonly} + */ + static readonly def: StructDef; + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {Readonly} + */ + static readonly elementSize: number; /** * Checks if input is a of Vec type. * diff --git a/dist/core.d.ts.map b/dist/core.d.ts.map index 30f9cbd..dd8bc3d 100644 --- a/dist/core.d.ts.map +++ b/dist/core.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;GAEG;AAYH,0BAAkB,QAAQ;IACtB,QAAQ,KAAK;IACb,qBAAqB,KAAK;IAC1B,sBAAsB,KAAK;CAC9B;AAKD,eAAO,MAAM,yBAAyB,yCAK5B,CAAA;AAEV;;;;;;;;;;;;;;;;;;;;GAoBG;AACF,qBAAa,GAAG,CAAC,CAAC,SAAS,SAAS;IAEhC;;;;;;;;;;;;;;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D,CAAC,MAAM,CAAC,CAAC,GACP,CAAC,CACC,aAAa,EAAE,CAAC,EAChB,YAAY,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EACpC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KACZ,CAAC,CAAC,CACV,CAAA"} \ No newline at end of file diff --git a/dist/core.js b/dist/core.js index 8053c7b..c72c44f 100644 --- a/dist/core.js +++ b/dist/core.js @@ -2242,3 +2242,21 @@ class Vec { } } exports.Vec = Vec; +/** + * The definition of an individual + * struct (element) in a vec class. + * @type {Readonly} + */ +Vec.def = {}; +/** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {Readonly} + */ +Vec.elementSize = 0; diff --git a/dist/index.d.ts b/dist/index.d.ts index d51d087..ce94775 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -58,6 +58,9 @@ export declare function validateStructDef(def: any): boolean; * @param {StructDef} structDef a type definition for the elements * to be carried by an instance of the generated vec * class + * @param {Object} [options] + * @param {string} [options.className=AnonymousVec] the value + * of the generated class's `name` property. Useful for debugging * @returns {VecClass} A class that creates vecs which conform * to inputted def * @@ -78,7 +81,9 @@ export declare function validateStructDef(def: any): boolean; * const errClass2 = vec({x: "unknownType"}) // SyntaxError * ``` */ -export declare function vec(structDef: S): VecClass; +export declare function vec(structDef: S, options?: { + className?: string; +}): VecClass; /** * A vec compiler that can be used at build time. * Creates class definitions for growable array-like @@ -116,7 +121,7 @@ export declare function vec(structDef: S): VecClass; * "none" (no import statement with class), "named" (use * the "export" syntax), or "default" (use "export default" * syntax). Defaults to "none". - * @param {string} [options.className="AnonymousVec"] the name of the generated + * @param {string} [options.className=AnonymousVec] the name of the generated * vec class. Defaults to "AnonymousVec". * @returns {string} a string rendition of vec class * @@ -154,6 +159,24 @@ export declare function vecCompile(structDef: StructDef, pathToLib: string, opti className: string; }>): string; export interface VecClass { + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {StructDef} + */ + readonly def: StructDef; + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {number} + */ + readonly elementSize: number; /** * Checks if input is a of Vec type. * diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map index c82cb92..1199d68 100644 --- a/dist/index.d.ts.map +++ b/dist/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAC,GAAG,IAAI,OAAO,EAAC,MAAM,QAAQ,CAAA;AACrC,OAAO,KAAK,EAAC,SAAS,EAAE,MAAM,EAAE,kBAAkB,EAAC,MAAM,QAAQ,CAAA;AAGjE,OAAO,EAAC,GAAG,EAAC,MAAM,QAAQ,CAAA;AAC1B,YAAY,EAAC,iBAAiB,EAAE,SAAS,EAAE,kBAAkB,GAAG,MAAM,QAAQ,CAAA;AAG9E,YAAY,EAAC,mBAAmB,EAAE,WAAW,EAAC,MAAM,QAAQ,CAAA;AAC5D,YAAY,EAAC,eAAe,EAAE,cAAc,EAAC,MAAM,QAAQ,CAAA;AAC3D,YAAY,EAAC,YAAY,EAAE,kBAAkB,EAAC,MAAM,QAAQ,CAAA;AAG5D,YAAY,EAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAC,MAAM,QAAQ,CAAA;AAChD,YAAY,EAAC,YAAY,EAAE,SAAS,EAAC,MAAM,QAAQ,CAAA;AACnD,YAAY,EAAC,MAAM,EAAE,SAAS,GAAE,MAAM,QAAQ,CAAA;AAE9C;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAOnD;A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E,OAAO,CAAC;IACb,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;IACjB,YAAY,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAA;IAC1C,SAAS,EAAE,MAAM,CAAA;CACpB,CAAM,GACR,MAAM,CAiBR;AAED,MAAM,WAAW,QAAQ,CAAC,CAAC,SAAS,SAAS;IACzC;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAA;IAEtB;;;;;;;;;;OAUG;IACJ,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;IACH,KAAK,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CAAA;IAC9B;;;;;;;;;;;;;;;;OAgBG;IACH,KAAK,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+CG;IACH,UAAU,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAClD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IACzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;CAC5C;;;;;;;AAED,wBAKC"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index ebe4c23..2f6c215 100644 --- a/dist/index.js +++ b/dist/index.js @@ -65,6 +65,9 @@ exports.validateStructDef = validateStructDef; * @param {StructDef} structDef a type definition for the elements * to be carried by an instance of the generated vec * class + * @param {Object} [options] + * @param {string} [options.className=AnonymousVec] the value + * of the generated class's `name` property. Useful for debugging * @returns {VecClass} A class that creates vecs which conform * to inputted def * @@ -85,21 +88,25 @@ exports.validateStructDef = validateStructDef; * const errClass2 = vec({x: "unknownType"}) // SyntaxError * ``` */ -function vec(structDef) { +function vec(structDef, options = {}) { if (typeof SharedArrayBuffer === "undefined") { throw new Error(`${compiler_1.ERR_PREFIX} sharedArrayBuffers are not supported in this environment and are required for vecs`); } const tokens = (0, compiler_1.tokenizeStructDef)(structDef); - const { def, className } = (0, compiler_1.createVecDef)(tokens, structDef, { + const { className = "AnonymousVec" } = options; + if ((0, compiler_1.invalidClassName)(className)) { + throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${className}"`); + } + const { def, className: clsName } = (0, compiler_1.createVecDef)(tokens, structDef, { lang: "js", exportSyntax: "none", pathToLib: "none", - className: "AnonymousVec", + className, runtimeCompile: true }); const genericVec = Function(`"use strict";return (Vec) => { ${def} - return ${className} + return ${clsName} }`)()(core_1.Vec); return genericVec; } @@ -141,7 +148,7 @@ exports.vec = vec; * "none" (no import statement with class), "named" (use * the "export" syntax), or "default" (use "export default" * syntax). Defaults to "none". - * @param {string} [options.className="AnonymousVec"] the name of the generated + * @param {string} [options.className=AnonymousVec] the name of the generated * vec class. Defaults to "AnonymousVec". * @returns {string} a string rendition of vec class * diff --git a/package.json b/package.json index 573eff5..06c270a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "test:lib": "jest --runInBand ./src", "test:codegen": "node ./codegenTests/codegen.mjs && node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --config=./codegenTests/jest.config.mjs ./codegenTests", "test:watch": "jest --runInBand --watchAll ./src", - "test:dev": "jest --runInBand ./src/tests/generation", + "test:dev": "jest --runInBand ./src/tests/naming", "bench:node": "node ./benchmarks/public/index.mjs", "bench:web": "nodemon ./benchmarks/server.mjs", "bench:deno": "deno run --allow-read benchmarks/public/index.mjs", diff --git a/scripts/docgen.mjs b/scripts/docgen.mjs index b903cb5..dfcd25a 100644 --- a/scripts/docgen.mjs +++ b/scripts/docgen.mjs @@ -10,8 +10,8 @@ const data = jsdoc2md.getTemplateDataSync({files: "dist/*.js"}) const rawDocs = jsdoc2md.renderSync({data}) const importAndAnchorMutations = rawDocs .replace( - /module_vec-struct.vec/gm, - "module_vec-struct.vec_gen", + /module_vec-struct..vec/gm, + "module_vec-struct..vec_gen", ) .replace( /from "struct-vec.js"/gm, diff --git a/src/compiler.ts b/src/compiler.ts index 6f950ea..9e3296a 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -214,6 +214,14 @@ function reservedJsKeyword(word: string): boolean { } } +export function invalidClassName(name: string): boolean { + return ( + !validVariableName(name) + || reservedJsKeyword(name) + || name.length < 1 + ) +} + export function validateCompileOptions(input: any) { if ( typeof input !== "object" @@ -231,9 +239,7 @@ export function validateCompileOptions(input: any) { if ( typeof input.className !== "string" - || !validVariableName(input.className) - || reservedJsKeyword(input.className) - || input.className.length < 1 + || invalidClassName(input.className) ) { throw SyntaxError(`inputted class name is not a valid javascript class name, got "${input.className}"`) } @@ -302,6 +308,8 @@ ${ts || runtimeCompile ${ exportSyntax === "named" ? "export " : "" }class ${className} extends Vec${ts ? generic : ""} { + static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} ${ts ? "protected " : ""}static Cursor = class Cursor { _viewingIndex = 0${ ts ? "\n\t\tself: Vec" + generic : "" diff --git a/src/core.ts b/src/core.ts index 60cb399..db55aca 100644 --- a/src/core.ts +++ b/src/core.ts @@ -50,7 +50,26 @@ export const VALID_DATA_TYPES_INTERNAL = [ * is type ```Vec``` */ export class Vec { - + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {Readonly} + */ + static readonly def: StructDef = {} + + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {Readonly} + */ + static readonly elementSize: number = 0 + /** * Checks if input is a of Vec type. * diff --git a/src/index.ts b/src/index.ts index 1f12678..2aee6f5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,7 @@ // imports should be one line only => for build system import {Vec as BaseVec} from "./core" import type {StructDef, Struct, ReadonlyInt32Array} from "./core" -import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions} from "./compiler" +import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions, invalidClassName} from "./compiler" export {Vec} from "./core" export type {CursorConstructor, VecCursor, ReadonlyInt32Array, } from "./core" @@ -75,6 +75,9 @@ export function validateStructDef(def: any): boolean { * @param {StructDef} structDef a type definition for the elements * to be carried by an instance of the generated vec * class + * @param {Object} [options] + * @param {string} [options.className=AnonymousVec] the value + * of the generated class's `name` property. Useful for debugging * @returns {VecClass} A class that creates vecs which conform * to inputted def * @@ -96,22 +99,31 @@ export function validateStructDef(def: any): boolean { * ``` */ export function vec( - structDef: S + structDef: S, + options: { + className?: string + } = {} ): VecClass { if (typeof SharedArrayBuffer === "undefined") { throw new Error(`${ERR_PREFIX} sharedArrayBuffers are not supported in this environment and are required for vecs`) } const tokens = tokenizeStructDef(structDef) - const {def, className} = createVecDef(tokens, structDef, { + const { + className = "AnonymousVec" + } = options + if (invalidClassName(className)) { + throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${className}"`) + } + const {def, className: clsName} = createVecDef(tokens, structDef, { lang: "js", exportSyntax: "none", pathToLib: "none", - className: "AnonymousVec", + className, runtimeCompile: true }) const genericVec = Function(`"use strict";return (Vec) => { ${def} - return ${className} + return ${clsName} }`)()(BaseVec) return genericVec } @@ -153,7 +165,7 @@ export function vec( * "none" (no import statement with class), "named" (use * the "export" syntax), or "default" (use "export default" * syntax). Defaults to "none". - * @param {string} [options.className="AnonymousVec"] the name of the generated + * @param {string} [options.className=AnonymousVec] the name of the generated * vec class. Defaults to "AnonymousVec". * @returns {string} a string rendition of vec class * @@ -213,6 +225,25 @@ export function vecCompile( } export interface VecClass { + /** + * The definition of an individual + * struct (element) in a vec class. + * @type {StructDef} + */ + readonly def: StructDef + + /** + * The amount of raw memory an individual + * struct (element of a vec) requires for vecs of this class. + * An individual block of memory corresponds to + * 4 bytes (32-bits). + * + * For example if ```elementSize``` is 2, each struct + * will take 8 bytes. + * + * @type {number} + */ + readonly elementSize: number /** * Checks if input is a of Vec type. * diff --git a/src/tests/generation.test.ts b/src/tests/generation.test.ts index 999d9ed..8c6758f 100644 --- a/src/tests/generation.test.ts +++ b/src/tests/generation.test.ts @@ -430,6 +430,26 @@ describe("bool data type", () => { }) }) +describe("class debug tools", () => { + it("class should have element size and definition accessible via static variables", () => { + const def = {a: "i32", b: "i32"} as const + const VecClass = vec(def) + expect(VecClass.def).toEqual(def) + expect(VecClass.elementSize).toBe(2) + }) + + it("vec class should return with inputted classname if specified", () => { + const VecClass = vec({a: "i32", b: "i32"}, { + className: "RandomVec" + }) + expect(VecClass.name).toEqual("RandomVec") + const VecClass2 = vec({a: "i32", b: "i32"}, { + className: "MyVec" + }) + expect(VecClass2.name).toEqual("MyVec") + }) +}) + describe("char data type", () => { it("single char field generated correctly", () => { diff --git a/src/tests/naming.test.ts b/src/tests/naming.test.ts index a237cee..f704554 100644 --- a/src/tests/naming.test.ts +++ b/src/tests/naming.test.ts @@ -20,6 +20,37 @@ describe("field name restrictions", () => { }) }) +describe("class naming restrictions", () => { + it("if class name is a js reserved keyword an error should be thrown", () => { + expect(() => {vec({a: "i32"}, {className: "await"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "for"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "let"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "const"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "while"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "if"})}).toThrow() + }) + + it("if class name does not follow naming convention for variables an error should be thrown", () => { + expect(() => {vec({a: "i32"}, {className: "my class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "my-class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "1class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "cl@ss"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "#class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "class&"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "class*"})}).toThrow() + }) + + it("if class name has unicode characters an error should be thrown", () => { + expect(() => {vec({a: "i32"}, {className: "myclass😙"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "my🏊‍♂️class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "❤️class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "cl💀ss"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "🔥class"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "class😂"})}).toThrow() + expect(() => {vec({a: "i32"}, {className: "✔️"})}).toThrow() + }) +}) + describe("schema restrictions", () => { it("inputting a non-object (including arrays & null) into schema field throws error", () => { expect(() => {vec(null as unknown as StructDef)}).toThrow() From 45233ee043ffaab4c56c80a8e0d06c2d022538e1 Mon Sep 17 00:00:00 2001 From: mostafa elbannan Date: Fri, 8 Apr 2022 18:59:20 -0700 Subject: [PATCH 2/5] added the ability to create references --- README.md | 48 ++++++++++ benchmarks/public/dist/compiler.js | 16 ++-- benchmarks/public/dist/core.js | 7 +- benchmarks/public/index.mjs | 63 +++++++++---- buildInfo/index.js.br | Bin 4932 -> 5004 bytes codegenTests/default-js.mjs | 14 +-- codegenTests/default.ts | 16 ++-- codegenTests/named-js.mjs | 14 +-- codegenTests/named.ts | 16 ++-- dist-deno/compiler.ts | 20 ++-- dist-deno/core.ts | 62 +++++++++++- dist-deno/index.ts | 3 +- dist-web/index.js | 40 ++++---- dist/compiler.d.ts.map | 2 +- dist/compiler.js | 16 ++-- dist/core.d.ts | 49 +++++++++- dist/core.d.ts.map | 2 +- dist/core.js | 47 +++++++++- dist/index.d.ts | 3 +- dist/index.d.ts.map | 2 +- package.json | 2 +- src/compiler.ts | 20 ++-- src/core.ts | 63 ++++++++++++- src/index.ts | 3 +- src/tests/references.test.ts | 146 +++++++++++++++++++++++++++++ 25 files changed, 556 insertions(+), 118 deletions(-) create mode 100644 src/tests/references.test.ts diff --git a/README.md b/README.md index 71593b8..6e29b84 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,10 @@ const p = new PositionV(20).fill({x: 1, y: 1, z: 1}) // cast to string const vecString = p.toJSON() +// can be casted to string like so as well +const vecString1 = JSON.stringify(p) console.log(typeof vecString) // output: "string" +console.log(vecString1 === vecString) // output: true // create vec from string const jsonVec = PositionV.fromString(vecString) @@ -1263,6 +1266,7 @@ Taken on ```March 31, 2022``` * [.sort(compareFn)](#module_vec-struct..Vec+sort) ⇒ Vec.<StructDef> * [.swap(aIndex, bIndex)](#module_vec-struct..Vec+swap) ⇒ Vec.<StructDef> * [.toJSON()](#module_vec-struct..Vec+toJSON) ⇒ string + * [.detachedCursor(index)](#module_vec-struct..Vec+detachedCursor) ⇒ DetachedVecCursor * _static_ * [.def](#module_vec-struct..Vec.def) : Readonly.<StructDef> * [.elementSize](#module_vec-struct..Vec.elementSize) : Readonly.<number> @@ -1339,6 +1343,7 @@ is type ```Vec``` * [.sort(compareFn)](#module_vec-struct..Vec+sort) ⇒ Vec.<StructDef> * [.swap(aIndex, bIndex)](#module_vec-struct..Vec+swap) ⇒ Vec.<StructDef> * [.toJSON()](#module_vec-struct..Vec+toJSON) ⇒ string + * [.detachedCursor(index)](#module_vec-struct..Vec+detachedCursor) ⇒ DetachedVecCursor * _static_ * [.def](#module_vec-struct..Vec.def) : Readonly.<StructDef> * [.elementSize](#module_vec-struct..Vec.elementSize) : Readonly.<number> @@ -2634,6 +2639,49 @@ jsonVec.forEach(pos => { console.log(pos.e) // output: {x: 1, y: 1, z: 1} }) ``` + + +#### vec.detachedCursor(index) ⇒ DetachedVecCursor +Creates an cursor that can be used to inspect/mutate +a vec, independent of the vec. It has +identical functionality as the ```Vec.index``` method, +expect that you can use it without the vec. + +**Kind**: instance method of [Vec](#module_vec-struct..Vec) + +| Param | Type | Description | +| --- | --- | --- | +| index | number | what index should the cursor initially point at | + +**Example** *(Basic Usage)* +```js +import {vec} from "struct-vec" + +const PositionV = vec({x: "f32", y: "f32", z: "f32"}) +const p = new PositionV() +p.push( + {x: 1, y: 1, z: 1}, + {x: 2, y: 2, z: 2}, + {x: 3, y: 3, z: 3}, +) + +// create a cursor and point it at index +// 0 +const cursorA = p.detachedCursor(0) +// create a cursor and point it at index +// 1 +const cursorB = p.detachedCursor(1) + +console.log(cursorA.e) // {x: 1, y: 1, z: 1} +console.log(cursorB.e) // {x: 2, y: 2, z: 2} +console.log(p.index(2).e) // {x: 3, y: 3, z: 3} + +// works like the "index" method of vecs +// but can be used independantly +cursorA.index(2).x = 55 +console.log(p.index(2).e) // {x: 55, y: 3, z: 3} +console.log(cursorA.e) // {x: 55, y: 3, z: 3} +``` #### Vec.def : Readonly.<StructDef> diff --git a/benchmarks/public/dist/compiler.js b/benchmarks/public/dist/compiler.js index 6676608..af8b501 100644 --- a/benchmarks/public/dist/compiler.js +++ b/benchmarks/public/dist/compiler.js @@ -221,7 +221,7 @@ export function createVecDef(tokens, structDef, { lang, pathToLib, className, ex const ts = lang === "ts"; const generic = `<${def}>`; const libPath = `"${pathToLib}"`; - const importStatement = `import {Vec${ts ? ", StructDef, Struct, CursorConstructor" : ""}} from ${libPath}`; + const importStatement = `import {Vec${ts ? ", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor" : ""}} from ${libPath}`; const CursorConstructor = "CursorConstructor" + generic; const memory = ts ? "(this.self as unknown as {_f32Memory: Float32Array})._f32Memory" @@ -239,11 +239,11 @@ ${ts || runtimeCompile * @extends {Vec${generic}} */`} ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? generic : ""} { - static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} - static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} - ${ts ? "protected " : ""}static Cursor = class Cursor { - _viewingIndex = 0${ts ? "\n\t\tself: Vec" + generic : ""} - constructor(self${ts ? ": Vec" + generic : ""}) { this.self = self } + static ${ts ? "readonly " : ""}def${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize${ts ? ": number" : ""} = ${elementSize} + ${ts ? "protected " : ""}static Cursor = class ${className}Cursor { + ${ts ? `_viewingIndex: number\n\t\tself: Vec${generic}` : ""} + constructor(self${ts ? ": Vec" + generic : ""}, index${ts ? ": number" : ""}) { this.self = self;this._viewingIndex = index} ${float32Fields.map(({ field, offset }) => { const fieldOffset = offset < 1 ? "" : (" + " + offset.toString()); const base = `${memory}[this._viewingIndex${fieldOffset}]`; @@ -284,7 +284,9 @@ ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? }).join(";")}; } get e()${ts ? ": Struct" + generic : ""} { return {${fieldNames.map((field) => { return field + ": this." + field; - }).join(", ")}} } + }).join(", ")}} } + get ref()${ts ? `: VecCursor${generic}` : ""} { return new ${className}.Cursor(this.self, this._viewingIndex) } + index(index${ts ? ": number" : ""})${ts ? `: DetachedVecCursor${generic}` : ""} { this._viewingIndex = index * this.self.elementSize; return this } }${ts ? " as " + CursorConstructor : ""} get elementSize()${ts ? ": number" : ""} { return ${elementSize} } get def()${ts ? ": StructDef" : ""} { return ${def} } diff --git a/benchmarks/public/dist/core.js b/benchmarks/public/dist/core.js index e4e170e..05dcc71 100644 --- a/benchmarks/public/dist/core.js +++ b/benchmarks/public/dist/core.js @@ -25,7 +25,7 @@ export class Vec { this._i32Memory = new Int32Array(buffer); this._length = vecLength; this._capacity = vecCapacity; - this._cursor = new this.cursorDef(this); + this._cursor = new this.cursorDef(this, 0); } catch (err) { throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`); @@ -644,7 +644,7 @@ export class Vec { if (this._length < 2) { return this; } - const helperCursor = new this.cursorDef(this); + const helperCursor = new this.cursorDef(this, 0); this.reserve(1); const elementSize = this.elementSize; const temporaryIndex = this._length * elementSize; @@ -701,6 +701,9 @@ export class Vec { memoryStr += `${this.elementSize},${this._capacity},${this._length}]`; return memoryStr; } + detachedCursor(index) { + return new this.cursorDef(this, index); + } createMemory(capacity) { const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT * this.elementSize diff --git a/benchmarks/public/index.mjs b/benchmarks/public/index.mjs index cab4c6e..73c65d3 100644 --- a/benchmarks/public/index.mjs +++ b/benchmarks/public/index.mjs @@ -2,40 +2,63 @@ import {vec} from "../../dist/index.js" import {Benchmark} from "./lib.mjs" const Position = vec({ - x: "f32", - y: "f32", - z: "f32" + x: "i32", + y: "i32", + z: "i32" }) const elementCount = 10_000_000 +const positionVec = new Position(1_000_000) +const positionArr = [] +const rawTypedArray = new Float32Array(elementCount * 3) + +for (let i = 0; i < elementCount; i += 1) { + positionArr.push({x: 1, y: 1, z: 1}) +} +for (let i = 0; i < elementCount; i += 1) { + positionVec.push({x: 1, y: 1, z: 1}) +} + +const tArrayLength = (elementCount * 3) + const benchmark = new Benchmark() benchmark -/* - .add("vec push", () => { - const container = new Position() - for (let i = 0; i < elementCount; i += 1) { - container.push({x: 1, y: 1, z: 1}) + .add("typed array imperative loop", () => { + for (let i = 0; i < tArrayLength; i += 3) { + rawTypedArray[i + 1] += 10 } }) - .add("arr push", () => { - const container = [] - for (let i = 0; i < elementCount; i += 1) { - container.push({x: 1, y: 1, z: 1}) + /* + .add("array iterator", () => { + positionArr.forEach(e => e.x += 10) + }) + */ + .add("array imperative loop", () => { + for (let i = 0; i < positionArr.length; i += 1) { + positionArr[i].y += 10 + } + }) + /* + .add("array es6 iterator", () => { + for (const position of positionArr) { + position.x += 10 } }) */ - .add("vec push with pre-alloc", () => { - const container = new Position() - container.reserve(elementCount) + .add("vec imperative loop", () => { for (let i = 0; i < elementCount; i += 1) { - container.push({x: 1, y: 1, z: 1}) + positionVec.index(i).y += 10 } }) - .add("arr push with pre-alloc", () => { - const container = new Array(elementCount) - for (let i = 0; i < elementCount; i += 1) { - container.push({x: 1, y: 1, z: 1}) + /* + .add("vec iterator", () => { + positionVec.forEach((e) => e.x += 10) + }) + .add("vec es6 iterator", () => { + for (const position of positionVec) { + position.x += 10 } }) + */ .run() diff --git a/buildInfo/index.js.br b/buildInfo/index.js.br index 94791f265fe0029390d6e6c35cfa35efa0fed39f..169c474280014d0944e545b182ae811a129e952d 100644 GIT binary patch literal 5004 zcmV;76Lahvbw>c41&(vx6p=O?k~F_EpCTy>5gQ@N>}EE5m(NRRGGHYl!1iaOJ+7;l z*)~x3N(ZN>qTT#i{?{+-VG>BSH?K6O)QV3CP|lI>Nn*=!Yo>}$YiWe=qMgzRzBpwW zay+HO?vh(WgOvHW{Ck^~XKwX?iBsUrxwAoEn64iEn(mg`(=E-^2^UbeM_L{5|6git zt2MKNC9RIoz!W+No#ez}KDCi;y_p#OuikIihB>>>x%u2VN<$JL4~6bgAXjZC{D=HR zkfv$nx`vnDN~%Fkrt~rL!u;h2A2GUp+Ooa{^SG6m8+eEPl`zusM@7JsuS|b5I_}y& zi<^L`344BP+n@zdzNZO>Wpwk{ZDzdloF8>`*8H=Yg&03v`X~$x;ZAhqaPOSvJC2Ml zn`ZH?4;L;+C<)#nyMb<$+ut=PH2nP%Z2a&EDx*=}jM4VaA+o5zzBx@-Wd07ve2@?- z)b|&8Zg?m=@f4)~`X_SC>#x(>v>ezS95lE8xDhdyY(uh2Jk`QqMIM(!_?*ZuE$tR0H;QR<&azG2>d@%_`^>`<5}=BVJ)f92dU7UDU_f2=;NPoE&{ zTOe)6QM}dZB9Hh)$dpBcq@I?A-%(@v0s<#G9DR<1JJi{W9Z=v#6o`$l&Rx{)1WZJIR`ViZWw zm-|kX)w-r{#pP$dNr5+|AxX!^0VNbLjj&0o`IzA=L{1bD|!j)Nhmka84XA)5Z4RK|2xqMM}hyzJOaUWwva1cG04%+1M~(p zAAX>L#vp5lS?nVPDdg(*bqO46H{e#-6k0#bZuUL|zg`cj?rHJ62&1^w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~CHZh7#KF$uyI-CPstT5g+%$(r?v zE+MP|tt-dS8r7J2wfz-g0ogr2~(9R#(2Zbt5po} zuEhi8Mh3{z=e5FL*o(=S%)G79b60X|dx0p~1M_udBl5|VInz@p!KhTX;Cd#=X8Ld3 z@~AzOp2`C<-T`K(#8>{fmCZPR)x=omR&kH} */ class DefaultJs extends Vec { - static def = {"x":"bool","y":"f32","z":"char"} - static elementSize = 3 - static Cursor = class Cursor { - _viewingIndex = 0 - constructor(self) { this.self = self } + static def = {"x":"bool","y":"f32","z":"char"} + static elementSize = 3 + static Cursor = class DefaultJsCursor { + + constructor(self, index) { this.self = self;this._viewingIndex = index} get y() { return this.self._f32Memory[this._viewingIndex] }; set y(newValue) { this.self._f32Memory[this._viewingIndex] = newValue }; get z() { return String.fromCodePoint(this.self._i32Memory[this._viewingIndex + 1] || 32) }; set z(newValue) { this.self._i32Memory[this._viewingIndex + 1] = newValue.codePointAt(0) || 32 }; get x() { return Boolean(this.self._i32Memory[this._viewingIndex + 2] & 1) }; set x(newValue) { this.self._i32Memory[this._viewingIndex + 2] &= -2;this.self._i32Memory[this._viewingIndex + 2] |= Boolean(newValue)}; set e({y, z, x}) { this.y = y;this.z = z;this.x = x; } - get e() { return {y: this.y, z: this.z, x: this.x} } + get e() { return {y: this.y, z: this.z, x: this.x} } + get ref() { return new DefaultJs.Cursor(this.self, this._viewingIndex) } + index(index) { this._viewingIndex = index * this.self.elementSize; return this } } get elementSize() { return 3 } get def() { return {"x":"bool","y":"f32","z":"char"} } diff --git a/codegenTests/default.ts b/codegenTests/default.ts index 7fc39e5..40bc46b 100644 --- a/codegenTests/default.ts +++ b/codegenTests/default.ts @@ -1,18 +1,20 @@ -import {Vec, StructDef, Struct, CursorConstructor} from "../dist" +import {Vec, StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor} from "../dist" class DefaultTs extends Vec<{"x":"bool","y":"f32","z":"char"}> { - static readonly def : StructDef = {"x":"bool","y":"f32","z":"char"} - static readonly elementSize : number = 3 - protected static Cursor = class Cursor { - _viewingIndex = 0 + static readonly def: StructDef = {"x":"bool","y":"f32","z":"char"} + static readonly elementSize: number = 3 + protected static Cursor = class DefaultTsCursor { + _viewingIndex: number self: Vec<{"x":"bool","y":"f32","z":"char"}> - constructor(self: Vec<{"x":"bool","y":"f32","z":"char"}>) { this.self = self } + constructor(self: Vec<{"x":"bool","y":"f32","z":"char"}>, index: number) { this.self = self;this._viewingIndex = index} get y(): number { return (this.self as unknown as {_f32Memory: Float32Array})._f32Memory[this._viewingIndex] }; set y(newValue: number) { (this.self as unknown as {_f32Memory: Float32Array})._f32Memory[this._viewingIndex] = newValue }; get z(): string { return String.fromCodePoint((this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 1] || 32) }; set z(newValue: string) { (this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 1] = newValue.codePointAt(0) || 32 }; get x(): boolean { return Boolean((this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] & 1) }; set x(newValue: boolean) { (this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] &= -2;(this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] |= (Boolean(newValue) as unknown as number)}; set e({y, z, x}: Struct<{"x":"bool","y":"f32","z":"char"}>) { this.y = y;this.z = z;this.x = x; } - get e(): Struct<{"x":"bool","y":"f32","z":"char"}> { return {y: this.y, z: this.z, x: this.x} } + get e(): Struct<{"x":"bool","y":"f32","z":"char"}> { return {y: this.y, z: this.z, x: this.x} } + get ref(): VecCursor<{"x":"bool","y":"f32","z":"char"}> { return new DefaultTs.Cursor(this.self, this._viewingIndex) } + index(index: number): DetachedVecCursor<{"x":"bool","y":"f32","z":"char"}> { this._viewingIndex = index * this.self.elementSize; return this } } as CursorConstructor<{"x":"bool","y":"f32","z":"char"}> get elementSize(): number { return 3 } get def(): StructDef { return {"x":"bool","y":"f32","z":"char"} } diff --git a/codegenTests/named-js.mjs b/codegenTests/named-js.mjs index 11fa9bf..103ce78 100644 --- a/codegenTests/named-js.mjs +++ b/codegenTests/named-js.mjs @@ -3,17 +3,19 @@ import {Vec} from "../dist" * @extends {Vec<{"x":"bool","y":"f32","z":"char"}>} */ export class NamedJs extends Vec { - static def = {"x":"bool","y":"f32","z":"char"} - static elementSize = 3 - static Cursor = class Cursor { - _viewingIndex = 0 - constructor(self) { this.self = self } + static def = {"x":"bool","y":"f32","z":"char"} + static elementSize = 3 + static Cursor = class NamedJsCursor { + + constructor(self, index) { this.self = self;this._viewingIndex = index} get y() { return this.self._f32Memory[this._viewingIndex] }; set y(newValue) { this.self._f32Memory[this._viewingIndex] = newValue }; get z() { return String.fromCodePoint(this.self._i32Memory[this._viewingIndex + 1] || 32) }; set z(newValue) { this.self._i32Memory[this._viewingIndex + 1] = newValue.codePointAt(0) || 32 }; get x() { return Boolean(this.self._i32Memory[this._viewingIndex + 2] & 1) }; set x(newValue) { this.self._i32Memory[this._viewingIndex + 2] &= -2;this.self._i32Memory[this._viewingIndex + 2] |= Boolean(newValue)}; set e({y, z, x}) { this.y = y;this.z = z;this.x = x; } - get e() { return {y: this.y, z: this.z, x: this.x} } + get e() { return {y: this.y, z: this.z, x: this.x} } + get ref() { return new NamedJs.Cursor(this.self, this._viewingIndex) } + index(index) { this._viewingIndex = index * this.self.elementSize; return this } } get elementSize() { return 3 } get def() { return {"x":"bool","y":"f32","z":"char"} } diff --git a/codegenTests/named.ts b/codegenTests/named.ts index 491f132..783c218 100644 --- a/codegenTests/named.ts +++ b/codegenTests/named.ts @@ -1,18 +1,20 @@ -import {Vec, StructDef, Struct, CursorConstructor} from "../dist" +import {Vec, StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor} from "../dist" export class NamedTs extends Vec<{"x":"bool","y":"f32","z":"char"}> { - static readonly def : StructDef = {"x":"bool","y":"f32","z":"char"} - static readonly elementSize : number = 3 - protected static Cursor = class Cursor { - _viewingIndex = 0 + static readonly def: StructDef = {"x":"bool","y":"f32","z":"char"} + static readonly elementSize: number = 3 + protected static Cursor = class NamedTsCursor { + _viewingIndex: number self: Vec<{"x":"bool","y":"f32","z":"char"}> - constructor(self: Vec<{"x":"bool","y":"f32","z":"char"}>) { this.self = self } + constructor(self: Vec<{"x":"bool","y":"f32","z":"char"}>, index: number) { this.self = self;this._viewingIndex = index} get y(): number { return (this.self as unknown as {_f32Memory: Float32Array})._f32Memory[this._viewingIndex] }; set y(newValue: number) { (this.self as unknown as {_f32Memory: Float32Array})._f32Memory[this._viewingIndex] = newValue }; get z(): string { return String.fromCodePoint((this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 1] || 32) }; set z(newValue: string) { (this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 1] = newValue.codePointAt(0) || 32 }; get x(): boolean { return Boolean((this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] & 1) }; set x(newValue: boolean) { (this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] &= -2;(this.self as unknown as {_i32Memory: Int32Array})._i32Memory[this._viewingIndex + 2] |= (Boolean(newValue) as unknown as number)}; set e({y, z, x}: Struct<{"x":"bool","y":"f32","z":"char"}>) { this.y = y;this.z = z;this.x = x; } - get e(): Struct<{"x":"bool","y":"f32","z":"char"}> { return {y: this.y, z: this.z, x: this.x} } + get e(): Struct<{"x":"bool","y":"f32","z":"char"}> { return {y: this.y, z: this.z, x: this.x} } + get ref(): VecCursor<{"x":"bool","y":"f32","z":"char"}> { return new NamedTs.Cursor(this.self, this._viewingIndex) } + index(index: number): DetachedVecCursor<{"x":"bool","y":"f32","z":"char"}> { this._viewingIndex = index * this.self.elementSize; return this } } as CursorConstructor<{"x":"bool","y":"f32","z":"char"}> get elementSize(): number { return 3 } get def(): StructDef { return {"x":"bool","y":"f32","z":"char"} } diff --git a/dist-deno/compiler.ts b/dist-deno/compiler.ts index c5934ab..80749bf 100644 --- a/dist-deno/compiler.ts +++ b/dist-deno/compiler.ts @@ -262,7 +262,7 @@ export function createVecDef( const generic = `<${def}>` const libPath = `"${pathToLib}"` const importStatement = `import {Vec${ - ts ? ", StructDef, Struct, CursorConstructor" : "" + ts ? ", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor" : "" }} from ${libPath}` const CursorConstructor = "CursorConstructor" + generic const memory = ts ? @@ -284,15 +284,17 @@ ${ts || runtimeCompile ${ exportSyntax === "named" ? "export " : "" }class ${className} extends Vec${ts ? generic : ""} { - static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} - static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} - ${ts ? "protected " : ""}static Cursor = class Cursor { - _viewingIndex = 0${ - ts ? "\n\t\tself: Vec" + generic : "" + static ${ts ? "readonly " : ""}def${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize${ts ? ": number" : ""} = ${elementSize} + ${ts ? "protected " : ""}static Cursor = class ${className}Cursor { + ${ + ts ? `_viewingIndex: number\n\t\tself: Vec${generic}` : "" } constructor(self${ ts ? ": Vec" + generic : "" - }) { this.self = self } + }, index${ + ts ? ": number" : "" + }) { this.self = self;this._viewingIndex = index} ${float32Fields.map(({field, offset}) => { const fieldOffset = offset < 1 ? "" : (" + " + offset.toString()) const base = `${memory}[this._viewingIndex${fieldOffset}]` @@ -343,7 +345,9 @@ ${ fieldNames.map((field) => { return field + ": this." + field }).join(", ") - }} } + }} } + get ref()${ts ? `: VecCursor${generic}`: ""} { return new ${className}.Cursor(this.self, this._viewingIndex) } + index(index${ts ? ": number" : ""})${ts? `: DetachedVecCursor${generic}` : ""} { this._viewingIndex = index * this.self.elementSize; return this } }${ts ? " as " + CursorConstructor : ""} get elementSize()${ts ? ": number" : ""} { return ${elementSize} } get def()${ts ? ": StructDef" : ""} { return ${def} } diff --git a/dist-deno/core.ts b/dist-deno/core.ts index 0fd4d3b..5f92a61 100644 --- a/dist-deno/core.ts +++ b/dist-deno/core.ts @@ -285,7 +285,7 @@ export const VALID_DATA_TYPES_INTERNAL = [ this._i32Memory = new Int32Array(buffer) this._length = vecLength this._capacity = vecCapacity - this._cursor = new this.cursorDef(this) + this._cursor = new this.cursorDef(this, 0) } catch (err) { throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`) } @@ -2189,7 +2189,7 @@ export const VALID_DATA_TYPES_INTERNAL = [ if (this._length < 2) { return this } - const helperCursor = new this.cursorDef(this) + const helperCursor = new this.cursorDef(this, 0) this.reserve(1) const elementSize = this.elementSize const temporaryIndex = this._length * elementSize @@ -2356,6 +2356,49 @@ export const VALID_DATA_TYPES_INTERNAL = [ memoryStr += `${this.elementSize},${this._capacity},${this._length}]` return memoryStr } + /** + * Creates an cursor that can be used to inspect/mutate + * a vec, independent of the vec. It has + * identical functionality as the ```Vec.index``` method, + * expect that you can use it without the vec. + * + * @param {number} index what index should the cursor + * initially point at + * @returns {DetachedVecCursor} + * + * @example Basic Usage + * ```js + * import {vec} from "struct-vec.ts" + * + * const PositionV = vec({x: "f32", y: "f32", z: "f32"}) + * const p = new PositionV() + * p.push( + * {x: 1, y: 1, z: 1}, + * {x: 2, y: 2, z: 2}, + * {x: 3, y: 3, z: 3}, + * ) + * + * + * + * const cursorA = p.detachedCursor(0) + * + * + * const cursorB = p.detachedCursor(1) + * + * console.log(cursorA.e) + * console.log(cursorB.e) + * console.log(p.index(2).e) + * + * + * + * cursorA.index(2).x = 55 + * console.log(p.index(2).e) + * console.log(cursorA.e) + * ``` + */ + detachedCursor(index: number): DetachedVecCursor { + return new this.cursorDef(this, index) + } private createMemory(capacity: number): SharedArrayBuffer { const elementsMemory = ( MEMORY_LAYOUT.BYTES_PER_ELEMENT @@ -2443,13 +2486,22 @@ export interface ReadonlyInt32Array extends Omit< } export type VecCursor = ( Struct - & {e: Struct} + & { + e: Struct, + ref: VecCursor + } ) +export type DetachedVecCursor = ( + VecCursor + & { + index: (index: number) => DetachedVecCursor + } +) export type CursorConstructor = { - new (self: Vec): VecCursorInternals + new (self: Vec, index: number): VecCursorInternals } type VecCursorInternals = ( - VecCursor + DetachedVecCursor & { _viewingIndex: number self: Vec diff --git a/dist-deno/index.ts b/dist-deno/index.ts index 7831e5d..59d9202 100644 --- a/dist-deno/index.ts +++ b/dist-deno/index.ts @@ -5,7 +5,8 @@ import {Vec as BaseVec} from "./core.ts" import type {StructDef, Struct, ReadonlyInt32Array} from "./core.ts" import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions, invalidClassName} from "./compiler.ts" export {Vec} from "./core.ts" -export type {CursorConstructor, VecCursor, ReadonlyInt32Array, } from "./core.ts" +export type {CursorConstructor, VecCursor, ReadonlyInt32Array} from "./core.ts" +export type {DetachedVecCursor} from "./core.ts" export type {SortCompareCallback, MapCallback} from "./core.ts" export type {ForEachCallback, ReduceCallback} from "./core.ts" export type {MapvCallback, TruthyIterCallback} from "./core.ts" diff --git a/dist-web/index.js b/dist-web/index.js index afed7e3..d916f5f 100644 --- a/dist-web/index.js +++ b/dist-web/index.js @@ -1,33 +1,35 @@ -var structVec=(()=>{var T=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)T(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&T(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(T({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>B,vec:()=>D,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,k=["f32","i32","char","bool"],v=class{constructor(e=15,t){try{let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this)}catch(n){throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${n}`)}}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,u=r*n;return l.copyWithin(0,a,u),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){try{let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}catch(t){throw console.error("Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation",t),t}}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,u=c*s,m=s,y=a+m,f=y;for(this._length=o;fs)try{let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,u=new N(a),m=new M(u);m.set(this._f32Memory),this.replaceMemory(m),this._capacity=c}catch(o){throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${o}`)}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let u=r;un.length){let u=r+n.length;for(let x=r;x=s?this:(this._f32Memory=this.shrinkCapacity(r),this._capacity=r,this)}catch(t){throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${t}`)}}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${f?", StructDef, Struct, CursorConstructor":""}} from ${x}`,L="CursorConstructor"+d,P=f?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=f?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` +var structVec=(()=>{var T=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)T(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&T(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(T({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,C=["f32","i32","char","bool"],v=class{constructor(e=15,t){try{let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this,0)}catch(n){throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${n}`)}}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,u=r*n;return l.copyWithin(0,a,u),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){try{let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}catch(t){throw console.error("Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation",t),t}}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,u=c*s,d=s,y=a+d,f=y;for(this._length=o;fs)try{let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,u=new N(a),d=new M(u);d.set(this._f32Memory),this.replaceMemory(d),this._capacity=c}catch(o){throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${o}`)}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let u=r;un.length){let u=r+n.length;for(let x=r;x=s?this:(this._f32Memory=this.shrinkCapacity(r),this._capacity=r,this)}catch(t){throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${t}`)}}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this,0);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${f?", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor":""}} from ${x}`,D="CursorConstructor"+g,P=f?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=f?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` ${n!=="none"?z:""} ${f||r?"":`/** - * @extends {Vec${d}} + * @extends {Vec${g}} */`} -${i==="named"?"export ":""}class ${s} extends Vec${f?d:""} { - static ${f?"readonly ":""}def ${f?": StructDef":""} = ${y} - static ${f?"readonly ":""}elementSize ${f?": number":""} = ${o} - ${f?"protected ":""}static Cursor = class Cursor { - _viewingIndex = 0${f?` - self: Vec`+d:""} - constructor(self${f?": Vec"+d:""}) { this.self = self } - ${l.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${P}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${g}()${p} { return ${w} }`,S=`set ${g}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` +${i==="named"?"export ":""}class ${s} extends Vec${f?g:""} { + static ${f?"readonly ":""}def${f?": StructDef":""} = ${y} + static ${f?"readonly ":""}elementSize${f?": number":""} = ${o} + ${f?"protected ":""}static Cursor = class ${s}Cursor { + ${f?`_viewingIndex: number + self: Vec${g}`:""} + constructor(self${f?": Vec"+g:""}, index${f?": number":""}) { this.self = self;this._viewingIndex = index} + ${l.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${P}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${m.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${g}()${p} { return ${w} }`,S=`set ${g}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` + ${d.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${u.map(({field:g,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": string":"",E=`get ${g}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${g}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${E}; ${S};`}).join(` + ${u.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": string":"",E=`get ${m}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${m}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${E}; ${S};`}).join(` `)} - ${a.map(({field:g,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,E=~p,S=f?": boolean":"",Y=f?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",A=`${V}[this._viewingIndex${w}]`,J=`get ${g}()${S} { return Boolean(${A} & ${p}) }`,q=`set ${g}(newValue${S}) { ${A} &= ${E};${A} |= ${Y}${$<1?"":" << "+$.toString()}}`;return`${J}; ${q};`}).join(` + ${a.map(({field:m,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,E=~p,S=f?": boolean":"",Y=f?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",A=`${V}[this._viewingIndex${w}]`,J=`get ${m}()${S} { return Boolean(${A} & ${p}) }`,q=`set ${m}(newValue${S}) { ${A} &= ${E};${A} |= ${Y}${$<1?"":" << "+$.toString()}}`;return`${J}; ${q};`}).join(` `)} - set e({${c.map(g=>g).join(", ")}}${f?": Struct"+d:""}) { ${c.map(g=>"this."+g+" = "+g).join(";")}; } - get e()${f?": Struct"+d:""} { return {${c.map(g=>g+": this."+g).join(", ")}} } - }${f?" as "+L:""} + set e({${c.map(m=>m).join(", ")}}${f?": Struct"+g:""}) { ${c.map(m=>"this."+m+" = "+m).join(";")}; } + get e()${f?": Struct"+g:""} { return {${c.map(m=>m+": this."+m).join(", ")}} } + get ref()${f?`: VecCursor${g}`:""} { return new ${s}.Cursor(this.self, this._viewingIndex) } + index(index${f?": number":""})${f?`: DetachedVecCursor${g}`:""} { this._viewingIndex = index * this.self.elementSize; return this } + }${f?" as "+D:""} get elementSize()${f?": number":""} { return ${o} } get def()${f?": StructDef":""} { return ${y} } - ${f?"protected ":""}get cursorDef()${f?": "+L:""} { return ${s}.Cursor } + ${f?"protected ":""}get cursorDef()${f?": "+D:""} { return ${s}.Cursor } } ${i==="default"?`export default {${s}}`:""} -`.trim()}}function B(h){try{return b(h),!0}catch(e){return!1}}function D(h,e={}){if(typeof SharedArrayBuffer=="undefined")throw new Error(`${I} sharedArrayBuffers are not supported in this environment and are required for vecs`);let t=b(h),{className:n="AnonymousVec"}=e;if(W(n))throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${n}"`);let{def:s,className:i}=C(t,h,{lang:"js",exportSyntax:"none",pathToLib:"none",className:n,runtimeCompile:!0});return Function(`"use strict";return (Vec) => { +`.trim()}}function j(h){try{return b(h),!0}catch(e){return!1}}function B(h,e={}){if(typeof SharedArrayBuffer=="undefined")throw new Error(`${I} sharedArrayBuffers are not supported in this environment and are required for vecs`);let t=b(h),{className:n="AnonymousVec"}=e;if(F(n))throw SyntaxError(`inputted class name (className option) is not a valid javascript class name, got "${n}"`);let{def:s,className:i}=W(t,h,{lang:"js",exportSyntax:"none",pathToLib:"none",className:n,runtimeCompile:!0});return Function(`"use strict";return (Vec) => { ${s} return ${i} - }`)()(v)}function O(h,e,t={}){let{lang:n="js",exportSyntax:s="none",className:i="AnonymousVec"}=t,r={lang:n,pathToLib:e,className:i,exportSyntax:s,runtimeCompile:!1};j(r);let o=b(h),{def:c}=C(o,h,r);return c}var se={vec:D,Vec:v,validateStructDef:B,vecCompile:O};return K(ie);})(); + }`)()(v)}function O(h,e,t={}){let{lang:n="js",exportSyntax:s="none",className:i="AnonymousVec"}=t,r={lang:n,pathToLib:e,className:i,exportSyntax:s,runtimeCompile:!1};R(r);let o=b(h),{def:c}=W(o,h,r);return c}var se={vec:B,Vec:v,validateStructDef:j,vecCompile:O};return K(ie);})(); diff --git a/dist/compiler.d.ts.map b/dist/compiler.d.ts.map index 800209a..92d491a 100644 --- a/dist/compiler.d.ts.map +++ b/dist/compiler.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"compiler.d.ts","sourceRoot":"","sources":["../src/compiler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAsC,MAAM,QAAQ,CAAA;AAKrE,eAAO,MAAM,UAAU,mBAAmB,CAAA;AAM1C,aAAK,cAAc,GAAG;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,aAAa,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;IAChD,WAAW,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;IAC9C,aAAa,EAAE;QACX,KAAK,EAAE,MAAM,CAAA;QACb,MAAM,EAAE,MAAM,CAAA;QACd,UAAU,EAAE,MAAM,CAAA;KACrB,EAAE,CAAC;IACJ,UAAU,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,EAAE,CAAA;CAChD,CAAA;AA6BD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,GAAG,GAAG,cAAc,CA8G1D;AAuDD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMtD;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,GAAG,QAkChD;AAED,aAA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AAE,MAAM,GAAG,OAAO,CAMtD;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,GAAG,QAkChD;AAED,aAAK,UAAU,GAAG;IACd,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAA;IAC1C,cAAc,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED,wBAAgB,YAAY,CACxB,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,SAAS,EACpB,EACI,IAAI,EACJ,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACjB,EAAE,UAAU,GACd;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAC,CAyGlC"} \ No newline at end of file diff --git a/dist/compiler.js b/dist/compiler.js index 06908d1..e5dd805 100644 --- a/dist/compiler.js +++ b/dist/compiler.js @@ -229,7 +229,7 @@ function createVecDef(tokens, structDef, { lang, pathToLib, className, exportSyn const ts = lang === "ts"; const generic = `<${def}>`; const libPath = `"${pathToLib}"`; - const importStatement = `import {Vec${ts ? ", StructDef, Struct, CursorConstructor" : ""}} from ${libPath}`; + const importStatement = `import {Vec${ts ? ", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor" : ""}} from ${libPath}`; const CursorConstructor = "CursorConstructor" + generic; const memory = ts ? "(this.self as unknown as {_f32Memory: Float32Array})._f32Memory" @@ -247,11 +247,11 @@ ${ts || runtimeCompile * @extends {Vec${generic}} */`} ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? generic : ""} { - static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} - static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} - ${ts ? "protected " : ""}static Cursor = class Cursor { - _viewingIndex = 0${ts ? "\n\t\tself: Vec" + generic : ""} - constructor(self${ts ? ": Vec" + generic : ""}) { this.self = self } + static ${ts ? "readonly " : ""}def${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize${ts ? ": number" : ""} = ${elementSize} + ${ts ? "protected " : ""}static Cursor = class ${className}Cursor { + ${ts ? `_viewingIndex: number\n\t\tself: Vec${generic}` : ""} + constructor(self${ts ? ": Vec" + generic : ""}, index${ts ? ": number" : ""}) { this.self = self;this._viewingIndex = index} ${float32Fields.map(({ field, offset }) => { const fieldOffset = offset < 1 ? "" : (" + " + offset.toString()); const base = `${memory}[this._viewingIndex${fieldOffset}]`; @@ -292,7 +292,9 @@ ${exportSyntax === "named" ? "export " : ""}class ${className} extends Vec${ts ? }).join(";")}; } get e()${ts ? ": Struct" + generic : ""} { return {${fieldNames.map((field) => { return field + ": this." + field; - }).join(", ")}} } + }).join(", ")}} } + get ref()${ts ? `: VecCursor${generic}` : ""} { return new ${className}.Cursor(this.self, this._viewingIndex) } + index(index${ts ? ": number" : ""})${ts ? `: DetachedVecCursor${generic}` : ""} { this._viewingIndex = index * this.self.elementSize; return this } }${ts ? " as " + CursorConstructor : ""} get elementSize()${ts ? ": number" : ""} { return ${elementSize} } get def()${ts ? ": StructDef" : ""} { return ${def} } diff --git a/dist/core.d.ts b/dist/core.d.ts index 25c686c..5258d68 100644 --- a/dist/core.d.ts +++ b/dist/core.d.ts @@ -1575,6 +1575,47 @@ export declare class Vec { * ``` */ toJSON(): string; + /** + * Creates an cursor that can be used to inspect/mutate + * a vec, independent of the vec. It has + * identical functionality as the ```Vec.index``` method, + * expect that you can use it without the vec. + * + * @param {number} index what index should the cursor + * initially point at + * @returns {DetachedVecCursor} + * + * @example Basic Usage + * ```js + * import {vec} from "struct-vec" + * + * const PositionV = vec({x: "f32", y: "f32", z: "f32"}) + * const p = new PositionV() + * p.push( + * {x: 1, y: 1, z: 1}, + * {x: 2, y: 2, z: 2}, + * {x: 3, y: 3, z: 3}, + * ) + * + * // create a cursor and point it at index + * // 0 + * const cursorA = p.detachedCursor(0) + * // create a cursor and point it at index + * // 1 + * const cursorB = p.detachedCursor(1) + * + * console.log(cursorA.e) // {x: 1, y: 1, z: 1} + * console.log(cursorB.e) // {x: 2, y: 2, z: 2} + * console.log(p.index(2).e) // {x: 3, y: 3, z: 3} + * + * // works like the "index" method of vecs + * // but can be used independantly + * cursorA.index(2).x = 55 + * console.log(p.index(2).e) // {x: 55, y: 3, z: 3} + * console.log(cursorA.e) // {x: 55, y: 3, z: 3} + * ``` + */ + detachedCursor(index: number): DetachedVecCursor; private createMemory; private shrinkCapacity; private deallocateExcessMemory; @@ -1598,11 +1639,15 @@ export interface ReadonlyInt32Array extends Omit = (Struct & { e: Struct; + ref: VecCursor; +}); +export declare type DetachedVecCursor = (VecCursor & { + index: (index: number) => DetachedVecCursor; }); export declare type CursorConstructor = { - new (self: Vec): VecCursorInternals; + new (self: Vec, index: number): VecCursorInternals; }; -declare type VecCursorInternals = (VecCursor & { +declare type VecCursorInternals = (DetachedVecCursor & { _viewingIndex: number; self: Vec; }); diff --git a/dist/core.d.ts.map b/dist/core.d.ts.map index dd8bc3d..5ba13ff 100644 --- a/dist/core.d.ts.map +++ b/dist/core.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;GAEG;AAYH,0BAAkB,QAAQ;IACtB,QAAQ,KAAK;IACb,qBAAqB,KAAK;IAC1B,sBAAsB,KAAK;CAC9B;AAKD,eAAO,MAAM,yBAAyB,yCAK5B,CAAA;AAEV;;;;;;;;;;;;;;;;;;;;GAoBG;AACF,qBAAa,GAAG,CAAC,CAAC,SAAS,SAAS;IACjC;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAK;IAEnC;;;;;;;;;;OAUG;IACH,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAI;IAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACZ,MAAM,CAAC,CAAC,CAAC,CAAC,CAClB,CAAA;AACD,oBAAY,kBAAkB,CAAC,CAAC,SAAS,SAAS,IAAI,CAClD,CAAC,MAAM,OAAO,CAAC,GACb,CAAC,CACH,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAC/B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KACR,OAAO,CAAC,CAChB,CAAA;AACD,oBAAY,cAAc,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,IAAI,CACjD,CAAC,MAAM,CAAC,CAAC,GACP,CAAC,CACC,aAAa,EAAE,CAAC,EAChB,YAAY,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EACpC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KACZ,CAAC,CAAC,CACV,CAAA"} \ No newline at end of file diff --git a/dist/core.js b/dist/core.js index c72c44f..0d8e748 100644 --- a/dist/core.js +++ b/dist/core.js @@ -69,7 +69,7 @@ class Vec { this._i32Memory = new Int32Array(buffer); this._length = vecLength; this._capacity = vecCapacity; - this._cursor = new this.cursorDef(this); + this._cursor = new this.cursorDef(this, 0); } catch (err) { throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`); @@ -2077,7 +2077,7 @@ class Vec { if (this._length < 2) { return this; } - const helperCursor = new this.cursorDef(this); + const helperCursor = new this.cursorDef(this, 0); this.reserve(1); const elementSize = this.elementSize; const temporaryIndex = this._length * elementSize; @@ -2204,6 +2204,49 @@ class Vec { memoryStr += `${this.elementSize},${this._capacity},${this._length}]`; return memoryStr; } + /** + * Creates an cursor that can be used to inspect/mutate + * a vec, independent of the vec. It has + * identical functionality as the ```Vec.index``` method, + * expect that you can use it without the vec. + * + * @param {number} index what index should the cursor + * initially point at + * @returns {DetachedVecCursor} + * + * @example Basic Usage + * ```js + * import {vec} from "struct-vec" + * + * const PositionV = vec({x: "f32", y: "f32", z: "f32"}) + * const p = new PositionV() + * p.push( + * {x: 1, y: 1, z: 1}, + * {x: 2, y: 2, z: 2}, + * {x: 3, y: 3, z: 3}, + * ) + * + * // create a cursor and point it at index + * // 0 + * const cursorA = p.detachedCursor(0) + * // create a cursor and point it at index + * // 1 + * const cursorB = p.detachedCursor(1) + * + * console.log(cursorA.e) // {x: 1, y: 1, z: 1} + * console.log(cursorB.e) // {x: 2, y: 2, z: 2} + * console.log(p.index(2).e) // {x: 3, y: 3, z: 3} + * + * // works like the "index" method of vecs + * // but can be used independantly + * cursorA.index(2).x = 55 + * console.log(p.index(2).e) // {x: 55, y: 3, z: 3} + * console.log(cursorA.e) // {x: 55, y: 3, z: 3} + * ``` + */ + detachedCursor(index) { + return new this.cursorDef(this, index); + } createMemory(capacity) { const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT * this.elementSize diff --git a/dist/index.d.ts b/dist/index.d.ts index ce94775..2ead006 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -4,7 +4,8 @@ import { Vec as BaseVec } from "./core"; import type { StructDef, Struct, ReadonlyInt32Array } from "./core"; export { Vec } from "./core"; -export type { CursorConstructor, VecCursor, ReadonlyInt32Array, } from "./core"; +export type { CursorConstructor, VecCursor, ReadonlyInt32Array } from "./core"; +export type { DetachedVecCursor } from "./core"; export type { SortCompareCallback, MapCallback } from "./core"; export type { ForEachCallback, ReduceCallback } from "./core"; export type { MapvCallback, TruthyIterCallback } from "./core"; diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map index 1199d68..2590050 100644 --- a/dist/index.d.ts.map +++ b/dist/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAC,GAAG,IAAI,OAAO,EAAC,MAAM,QAAQ,CAAA;AACrC,OAAO,KAAK,EAAC,SAAS,EAAE,MAAM,EAAE,kBAAkB,EAAC,MAAM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CAAA;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;IACH,KAAK,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CAAA;IAC9B;;;;;;;;;;;;;;;;OAgBG;IACH,KAAK,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+CG;IACH,UAAU,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAClD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IACzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;CAC5C;;;;;;;AAED,wBAKC"} \ No newline at end of file diff --git a/package.json b/package.json index 06c270a..477aa8f 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "test:lib": "jest --runInBand ./src", "test:codegen": "node ./codegenTests/codegen.mjs && node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --config=./codegenTests/jest.config.mjs ./codegenTests", "test:watch": "jest --runInBand --watchAll ./src", - "test:dev": "jest --runInBand ./src/tests/naming", + "test:dev": "jest --runInBand ./src/tests/references", "bench:node": "node ./benchmarks/public/index.mjs", "bench:web": "nodemon ./benchmarks/server.mjs", "bench:deno": "deno run --allow-read benchmarks/public/index.mjs", diff --git a/src/compiler.ts b/src/compiler.ts index 9e3296a..cad2b3b 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -286,7 +286,7 @@ export function createVecDef( const generic = `<${def}>` const libPath = `"${pathToLib}"` const importStatement = `import {Vec${ - ts ? ", StructDef, Struct, CursorConstructor" : "" + ts ? ", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor" : "" }} from ${libPath}` const CursorConstructor = "CursorConstructor" + generic const memory = ts ? @@ -308,15 +308,17 @@ ${ts || runtimeCompile ${ exportSyntax === "named" ? "export " : "" }class ${className} extends Vec${ts ? generic : ""} { - static ${ts ? "readonly " : ""}def ${ts ? ": StructDef" : ""} = ${def} - static ${ts ? "readonly " : ""}elementSize ${ts ? ": number" : ""} = ${elementSize} - ${ts ? "protected " : ""}static Cursor = class Cursor { - _viewingIndex = 0${ - ts ? "\n\t\tself: Vec" + generic : "" + static ${ts ? "readonly " : ""}def${ts ? ": StructDef" : ""} = ${def} + static ${ts ? "readonly " : ""}elementSize${ts ? ": number" : ""} = ${elementSize} + ${ts ? "protected " : ""}static Cursor = class ${className}Cursor { + ${ + ts ? `_viewingIndex: number\n\t\tself: Vec${generic}` : "" } constructor(self${ ts ? ": Vec" + generic : "" - }) { this.self = self } + }, index${ + ts ? ": number" : "" + }) { this.self = self;this._viewingIndex = index} ${float32Fields.map(({field, offset}) => { const fieldOffset = offset < 1 ? "" : (" + " + offset.toString()) const base = `${memory}[this._viewingIndex${fieldOffset}]` @@ -367,7 +369,9 @@ ${ fieldNames.map((field) => { return field + ": this." + field }).join(", ") - }} } + }} } + get ref()${ts ? `: VecCursor${generic}`: ""} { return new ${className}.Cursor(this.self, this._viewingIndex) } + index(index${ts ? ": number" : ""})${ts? `: DetachedVecCursor${generic}` : ""} { this._viewingIndex = index * this.self.elementSize; return this } }${ts ? " as " + CursorConstructor : ""} get elementSize()${ts ? ": number" : ""} { return ${elementSize} } get def()${ts ? ": StructDef" : ""} { return ${def} } diff --git a/src/core.ts b/src/core.ts index db55aca..d117f9f 100644 --- a/src/core.ts +++ b/src/core.ts @@ -298,7 +298,7 @@ export const VALID_DATA_TYPES_INTERNAL = [ this._i32Memory = new Int32Array(buffer) this._length = vecLength this._capacity = vecCapacity - this._cursor = new this.cursorDef(this) + this._cursor = new this.cursorDef(this, 0) } catch (err) { throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`) } @@ -2269,7 +2269,7 @@ export const VALID_DATA_TYPES_INTERNAL = [ if (this._length < 2) { return this } - const helperCursor = new this.cursorDef(this) + const helperCursor = new this.cursorDef(this, 0) this.reserve(1) const elementSize = this.elementSize const temporaryIndex = this._length * elementSize @@ -2441,6 +2441,50 @@ export const VALID_DATA_TYPES_INTERNAL = [ return memoryStr } + /** + * Creates an cursor that can be used to inspect/mutate + * a vec, independent of the vec. It has + * identical functionality as the ```Vec.index``` method, + * expect that you can use it without the vec. + * + * @param {number} index what index should the cursor + * initially point at + * @returns {DetachedVecCursor} + * + * @example Basic Usage + * ```js + * import {vec} from "struct-vec" + * + * const PositionV = vec({x: "f32", y: "f32", z: "f32"}) + * const p = new PositionV() + * p.push( + * {x: 1, y: 1, z: 1}, + * {x: 2, y: 2, z: 2}, + * {x: 3, y: 3, z: 3}, + * ) + * + * // create a cursor and point it at index + * // 0 + * const cursorA = p.detachedCursor(0) + * // create a cursor and point it at index + * // 1 + * const cursorB = p.detachedCursor(1) + * + * console.log(cursorA.e) // {x: 1, y: 1, z: 1} + * console.log(cursorB.e) // {x: 2, y: 2, z: 2} + * console.log(p.index(2).e) // {x: 3, y: 3, z: 3} + * + * // works like the "index" method of vecs + * // but can be used independantly + * cursorA.index(2).x = 55 + * console.log(p.index(2).e) // {x: 55, y: 3, z: 3} + * console.log(cursorA.e) // {x: 55, y: 3, z: 3} + * ``` + */ + detachedCursor(index: number): DetachedVecCursor { + return new this.cursorDef(this, index) + } + private createMemory(capacity: number): SharedArrayBuffer { const elementsMemory = ( MEMORY_LAYOUT.BYTES_PER_ELEMENT @@ -2536,16 +2580,25 @@ export interface ReadonlyInt32Array extends Omit< export type VecCursor = ( Struct - & {e: Struct} + & { + e: Struct, + ref: VecCursor + } ) +export type DetachedVecCursor = ( + VecCursor + & { + index: (index: number) => DetachedVecCursor + } +) export type CursorConstructor = { - new (self: Vec): VecCursorInternals + new (self: Vec, index: number): VecCursorInternals } type VecCursorInternals = ( - VecCursor + DetachedVecCursor & { _viewingIndex: number self: Vec diff --git a/src/index.ts b/src/index.ts index 2aee6f5..7fdf1f1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,8 @@ import type {StructDef, Struct, ReadonlyInt32Array} from "./core" import {tokenizeStructDef, ERR_PREFIX, createVecDef, validateCompileOptions, invalidClassName} from "./compiler" export {Vec} from "./core" -export type {CursorConstructor, VecCursor, ReadonlyInt32Array, } from "./core" +export type {CursorConstructor, VecCursor, ReadonlyInt32Array} from "./core" +export type {DetachedVecCursor} from "./core" // Iterator callbacks export type {SortCompareCallback, MapCallback} from "./core" diff --git a/src/tests/references.test.ts b/src/tests/references.test.ts new file mode 100644 index 0000000..c830543 --- /dev/null +++ b/src/tests/references.test.ts @@ -0,0 +1,146 @@ +import {expect, it, describe} from "@jest/globals" +import {vec} from "../index" + +describe("references are independent from vec cursor", () => { + it("can point to different index", () => { + const Enemy = vec({power: "i32", isDead: "bool"}) + const orcs = new Enemy() + orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, + ) + const ref = orcs.index(0).ref + expect(orcs.index(1).e).toEqual({ + power: 13, + isDead: false + }) + expect(orcs.index(2).e).toEqual({ + power: 72, + isDead: false + }) + expect(ref.e).toEqual({ + power: 55, + isDead: false + }) + }) + + it("can mutate different indexes without influencing cursor's index", () => { + const Enemy = vec({power: "i32", isDead: "bool"}) + const orcs = new Enemy() + orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, + ) + const orc1 = orcs.index(0).ref + orc1.isDead = true + orc1.power = 0 + expect(orcs.index(1).e).toEqual({ + power: 13, + isDead: false + }) + expect(orcs.index(2).e).toEqual({ + power: 72, + isDead: false + }) + expect(orc1.e).toEqual({ + power: 0, + isDead: true + }) + }) + + it("multiple references pointing to the same memory can be created", () => { + const Enemy = vec({power: "i32", isDead: "bool"}) + const orcs = new Enemy() + orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, + ) + const ref1 = orcs.index(0).ref + ref1.isDead = true + ref1.power = 0 + expect(ref1.e).toEqual({ + power: 0, + isDead: true + }) + const ref2 = ref1.ref + expect(ref2.e).toEqual({ + power: 0, + isDead: true + }) + ref2.isDead = false + ref2.power = 10 + expect(ref2.e).toEqual({ + power: 10, + isDead: false + }) + expect(ref1.e).toEqual({ + power: 10, + isDead: false + }) + }) +}) + +describe("references point to an index not a particular element", () => { + it("ref does not point to a particular element", () => { + const Enemy = vec({power: "i32", isDead: "bool"}) + const orcs = new Enemy() + orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, + ) + const ref = orcs.index(0).ref + expect(ref.e).toEqual({ + power: 55, isDead: false + }) + orcs.swap(0, 1) + expect(ref.e).not.toEqual({ + power: 55, isDead: false + }) + expect(ref.e).toEqual({ + power: 13, isDead: false + }) + }) +}) + + +describe("detached references", () => { + it("detached references are just like normal references, except they can move positions", () => { + const Enemy = vec({power: "i32", isDead: "bool"}) + const orcs = new Enemy() + orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, + ) + const cursor = orcs.detachedCursor(0) + expect(orcs.index(1).e).toEqual({ + power: 13, + isDead: false + }) + expect(orcs.index(2).e).toEqual({ + power: 72, + isDead: false + }) + expect(cursor.e).toEqual({ + power: 55, + isDead: false + }) + expect(cursor.index(2).e).toEqual({ + power: 72, + isDead: false + }) + expect(orcs.index(1).e).toEqual({ + power: 13, + isDead: false + }) + cursor.index(1).power = 9_001 + expect(orcs.index(1).e).toEqual({ + power: 9_001, + isDead: false + }) + }) +}) \ No newline at end of file From 0e082cf39626e1f91e59dcf085ee278d9902e7ae Mon Sep 17 00:00:00 2001 From: mostafa elbannan Date: Sat, 9 Apr 2022 12:36:04 -0700 Subject: [PATCH 3/5] removed unneccessary try-catch blocks --- benchmarks/public/dist/core.js | 134 +++++++++++++----------------- benchmarks/public/index.mjs | 65 +++++---------- buildInfo/index.js.br | Bin 5004 -> 4904 bytes dist-deno/core.ts | 146 +++++++++++++++------------------ dist-web/index.js | 40 ++++----- dist/core.d.ts.map | 2 +- dist/core.js | 134 +++++++++++++----------------- package.json | 2 +- src/core.ts | 146 +++++++++++++++------------------ 9 files changed, 281 insertions(+), 388 deletions(-) diff --git a/benchmarks/public/dist/core.js b/benchmarks/public/dist/core.js index 05dcc71..3c798d9 100644 --- a/benchmarks/public/dist/core.js +++ b/benchmarks/public/dist/core.js @@ -8,28 +8,23 @@ export const VALID_DATA_TYPES_INTERNAL = [ ]; export class Vec { constructor(initialCapacity = 15, memory) { - try { - let vecCapacity = 0; - let vecLength = 0; - let buffer; - if (!memory) { - vecCapacity = Math.abs(initialCapacity); - buffer = this.createMemory(vecCapacity); - } - else { - vecLength = memory[memory.length - 1]; - vecCapacity = memory[memory.length - 2]; - buffer = memory.buffer; - } - this._f32Memory = new Float32Array(buffer); - this._i32Memory = new Int32Array(buffer); - this._length = vecLength; - this._capacity = vecCapacity; - this._cursor = new this.cursorDef(this, 0); + let vecCapacity = 0; + let vecLength = 0; + let buffer; + if (!memory) { + vecCapacity = Math.abs(initialCapacity); + buffer = this.createMemory(vecCapacity); } - catch (err) { - throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`); + else { + vecLength = memory[memory.length - 1]; + vecCapacity = memory[memory.length - 2]; + buffer = memory.buffer; } + this._f32Memory = new Float32Array(buffer); + this._i32Memory = new Int32Array(buffer); + this._length = vecLength; + this._capacity = vecCapacity; + this._cursor = new this.cursorDef(this, 0); } static isVec(candidate) { return candidate instanceof this; @@ -346,30 +341,24 @@ export class Vec { return this; } reserve(additional) { - try { - const elementSize = this.elementSize; - const length = this._length; - const capacity = this._capacity; - if (length + additional <= capacity) { - return; - } - const newCapacity = length + additional; - const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity); - const bufferSize = (8 - + elementsMemory); - const buffer = new BUFFER_TYPE(bufferSize); - const memory = new MEMORY_LAYOUT(buffer); - memory.set(this._f32Memory); - this.replaceMemory(memory); - this._capacity = newCapacity; - return this; - } - catch (err) { - console.error(`Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation`, err); - throw err; + const elementSize = this.elementSize; + const length = this._length; + const capacity = this._capacity; + if (length + additional <= capacity) { + return; } + const newCapacity = length + additional; + const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity); + const bufferSize = (8 + + elementsMemory); + const buffer = new BUFFER_TYPE(bufferSize); + const memory = new MEMORY_LAYOUT(buffer); + memory.set(this._f32Memory); + this.replaceMemory(memory); + this._capacity = newCapacity; + return this; } reverse() { const elementSize = this.elementSize; @@ -481,25 +470,20 @@ export class Vec { const capacity = this._capacity; const minimumCapcity = length + structs.length; if (minimumCapcity > capacity) { - try { - const targetCapacity = capacity * 2; - const newCapacity = minimumCapcity > targetCapacity - ? minimumCapcity + 15 - : targetCapacity; - const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity); - const bufferSize = (8 - + elementsMemory); - const buffer = new BUFFER_TYPE(bufferSize); - const memory = new MEMORY_LAYOUT(buffer); - memory.set(this._f32Memory); - this.replaceMemory(memory); - this._capacity = newCapacity; - } - catch (err) { - throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${err}`); - } + const targetCapacity = capacity * 2; + const newCapacity = minimumCapcity > targetCapacity + ? minimumCapcity + 15 + : targetCapacity; + const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity); + const bufferSize = (8 + + elementsMemory); + const buffer = new BUFFER_TYPE(bufferSize); + const memory = new MEMORY_LAYOUT(buffer); + memory.set(this._f32Memory); + this.replaceMemory(memory); + this._capacity = newCapacity; } const previousIndex = this._cursor._viewingIndex; for (let i = 0; i < structs.length; i += 1) { @@ -621,24 +605,18 @@ export class Vec { return newLength; } shrinkTo(minCapacity = 15) { - try { - const elementSize = this.elementSize; - const length = this._length; - const capacity = this._capacity; - const minCapacityNormalize = minCapacity < 0 - ? 0 - : minCapacity; - const newCapacity = length + minCapacityNormalize; - if (newCapacity >= capacity) { - return this; - } - this._f32Memory = this.shrinkCapacity(newCapacity); - this._capacity = newCapacity; + const length = this._length; + const capacity = this._capacity; + const minCapacityNormalize = minCapacity < 0 + ? 0 + : minCapacity; + const newCapacity = length + minCapacityNormalize; + if (newCapacity >= capacity) { return this; } - catch (err) { - throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${err}`); - } + this._f32Memory = this.shrinkCapacity(newCapacity); + this._capacity = newCapacity; + return this; } sort(compareFn) { if (this._length < 2) { diff --git a/benchmarks/public/index.mjs b/benchmarks/public/index.mjs index 73c65d3..f2e3548 100644 --- a/benchmarks/public/index.mjs +++ b/benchmarks/public/index.mjs @@ -1,64 +1,37 @@ import {vec} from "../../dist/index.js" import {Benchmark} from "./lib.mjs" -const Position = vec({ - x: "i32", - y: "i32", - z: "i32" -}) +const Position = vec({x: "f32", y: "f32", z: "f32"}) const elementCount = 10_000_000 -const positionVec = new Position(1_000_000) -const positionArr = [] -const rawTypedArray = new Float32Array(elementCount * 3) - -for (let i = 0; i < elementCount; i += 1) { - positionArr.push({x: 1, y: 1, z: 1}) -} -for (let i = 0; i < elementCount; i += 1) { - positionVec.push({x: 1, y: 1, z: 1}) -} - -const tArrayLength = (elementCount * 3) - const benchmark = new Benchmark() benchmark - .add("typed array imperative loop", () => { - for (let i = 0; i < tArrayLength; i += 3) { - rawTypedArray[i + 1] += 10 - } - }) - /* - .add("array iterator", () => { - positionArr.forEach(e => e.x += 10) - }) - */ - .add("array imperative loop", () => { - for (let i = 0; i < positionArr.length; i += 1) { - positionArr[i].y += 10 + .add("vec push", () => { + const container = new Position() + for (let i = 0; i < elementCount; i += 1) { + container.push({x: 1, y: 1, z: 1}) } }) - /* - .add("array es6 iterator", () => { - for (const position of positionArr) { - position.x += 10 + .add("arr push", () => { + const container = [] + for (let i = 0; i < elementCount; i += 1) { + container.push({x: 1, y: 1, z: 1}) } }) - */ - .add("vec imperative loop", () => { +/* + .add("vec push with pre-alloc", () => { + const container = new Position() + container.reserve(elementCount) for (let i = 0; i < elementCount; i += 1) { - positionVec.index(i).y += 10 + container.push({x: 1, y: 1, z: 1}) } }) - /* - .add("vec iterator", () => { - positionVec.forEach((e) => e.x += 10) - }) - .add("vec es6 iterator", () => { - for (const position of positionVec) { - position.x += 10 + .add("arr push with pre-alloc", () => { + const container = new Array(elementCount) + for (let i = 0; i < elementCount; i += 1) { + container.push({x: 1, y: 1, z: 1}) } }) - */ +*/ .run() diff --git a/buildInfo/index.js.br b/buildInfo/index.js.br index 169c474280014d0944e545b182ae811a129e952d..bbc6af0d5618cee489e893b9afe7fb2d95b1282b 100644 GIT binary patch literal 4904 zcmV+@6W8n;!9@V925e&(>xbz>kv^|Awn_7gMpH#ZMC=GjX7~M>e*JQOyc9Z3$9Bh@ zI6?+BuAEA`6>{wa5E3wcZ#uhkISrGhu|EoIZW7v3tJ%a5r8y5dbv$ONY1O_YhXb*s zLq6P+m7BuDp);iXR7%?lAUswYq|C?V|EZc)eh-9#Q*J}<+`Ch>%XazypFb7=5+{J9 z9)rXUl!Mlho6^iMEC^CMl2UexxhSvdQ!abGt?o{@i8z($DmQ%%vo7tw@66U11XKir zNw>E^uG~)eSA0cCP1B}Z8lJfuQuREU>|^A_`NNNIF{Zs+v$_TIu#=b*_=x^W7-{&6 zB;bi>r#~7U4^`jTOhD9_JxADvwuJUT`*y=TrUjgB0q#8K>-JCD>x-$(@MP)TFffDz zXy4(hy_TacG(HRUhN?=sKCB0 z+F6nLI~?a<|MoxPSlJt3TX`5OcO6Ss6^V@aHJQ zyo=uo<>~oTLh9K|WGIHrl{{UZ-S-(>e2i)49Y+ugIS(K4Gioj7+ujRzo8P9d{rqs7XSF8B-G%4^KbILf-DuFGQ1ck6( z!+UUHNf&BamIr|czK-VU!u|ysZBmNjsu$jq6(k5);BR3CfT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L = [ initialCapacity: number = defaults.capacity, memory?: ReadonlyInt32Array ) { - try { - let vecCapacity = 0 - let vecLength = 0 - let buffer: SharedArrayBuffer - if (!memory) { - vecCapacity = Math.abs(initialCapacity) - buffer = this.createMemory(vecCapacity) - } else { - vecLength = memory[memory.length - encoding.lengthReverseIndex] - vecCapacity = memory[memory.length - encoding.capacityReverseIndex] - buffer = memory.buffer as SharedArrayBuffer - } - this._f32Memory = new Float32Array(buffer) - this._i32Memory = new Int32Array(buffer) - this._length = vecLength - this._capacity = vecCapacity - this._cursor = new this.cursorDef(this, 0) - } catch (err) { - throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`) + let vecCapacity = 0 + let vecLength = 0 + let buffer: SharedArrayBuffer + if (!memory) { + vecCapacity = Math.abs(initialCapacity) + buffer = this.createMemory(vecCapacity) + } else { + vecLength = memory[memory.length - encoding.lengthReverseIndex] + vecCapacity = memory[memory.length - encoding.capacityReverseIndex] + buffer = memory.buffer as SharedArrayBuffer } + this._f32Memory = new Float32Array(buffer) + this._i32Memory = new Int32Array(buffer) + this._length = vecLength + this._capacity = vecCapacity + this._cursor = new this.cursorDef(this, 0) } /** * The amount of raw memory an individual @@ -1387,33 +1383,28 @@ export const VALID_DATA_TYPES_INTERNAL = [ * ``` */ reserve(additional: number) { - try { - const elementSize = this.elementSize - const length = this._length - const capacity = this._capacity - if (length + additional <= capacity) { - return - } - const newCapacity = length + additional - const elementsMemory = ( - MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity - ) - const bufferSize = ( - encoding.encodingBytes - + elementsMemory - ) - const buffer = new BUFFER_TYPE(bufferSize) - const memory = new MEMORY_LAYOUT(buffer) - memory.set(this._f32Memory) - this.replaceMemory(memory) - this._capacity = newCapacity - return this - } catch (err) { - console.error(`Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation`, err) - throw err + const elementSize = this.elementSize + const length = this._length + const capacity = this._capacity + if (length + additional <= capacity) { + return } + const newCapacity = length + additional + const elementsMemory = ( + MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity + ) + const bufferSize = ( + encoding.encodingBytes + + elementsMemory + ) + const buffer = new BUFFER_TYPE(bufferSize) + const memory = new MEMORY_LAYOUT(buffer) + memory.set(this._f32Memory) + this.replaceMemory(memory) + this._capacity = newCapacity + return this } /** * Reverses an vec in place. The first vec @@ -1728,28 +1719,24 @@ export const VALID_DATA_TYPES_INTERNAL = [ const capacity = this._capacity const minimumCapcity = length + structs.length if (minimumCapcity > capacity) { - try { - const targetCapacity = capacity * 2 - const newCapacity = minimumCapcity > targetCapacity - ? minimumCapcity + defaults.capacity - : targetCapacity - const elementsMemory = ( - MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity - ) - const bufferSize = ( - encoding.encodingBytes - + elementsMemory - ) - const buffer = new BUFFER_TYPE(bufferSize) - const memory = new MEMORY_LAYOUT(buffer) - memory.set(this._f32Memory) - this.replaceMemory(memory) - this._capacity = newCapacity - } catch (err) { - throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${err}`) - } + const targetCapacity = capacity * 2 + const newCapacity = minimumCapcity > targetCapacity + ? minimumCapcity + defaults.capacity + : targetCapacity + const elementsMemory = ( + MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity + ) + const bufferSize = ( + encoding.encodingBytes + + elementsMemory + ) + const buffer = new BUFFER_TYPE(bufferSize) + const memory = new MEMORY_LAYOUT(buffer) + memory.set(this._f32Memory) + this.replaceMemory(memory) + this._capacity = newCapacity } const previousIndex = this._cursor._viewingIndex for (let i = 0; i < structs.length; i += 1) { @@ -2089,23 +2076,18 @@ export const VALID_DATA_TYPES_INTERNAL = [ shrinkTo( minCapacity: number = defaults.capacity ): Vec { - try { - const elementSize = this.elementSize - const length = this._length - const capacity = this._capacity - const minCapacityNormalize = minCapacity < 0 - ? 0 - : minCapacity - const newCapacity = length + minCapacityNormalize - if (newCapacity >= capacity) { - return this - } - this._f32Memory = this.shrinkCapacity(newCapacity) - this._capacity = newCapacity + const length = this._length + const capacity = this._capacity + const minCapacityNormalize = minCapacity < 0 + ? 0 + : minCapacity + const newCapacity = length + minCapacityNormalize + if (newCapacity >= capacity) { return this - } catch (err) { - throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${err}`) } + this._f32Memory = this.shrinkCapacity(newCapacity) + this._capacity = newCapacity + return this } /** * Sorts the elements of an array in place and diff --git a/dist-web/index.js b/dist-web/index.js index d916f5f..2dece66 100644 --- a/dist-web/index.js +++ b/dist-web/index.js @@ -1,31 +1,31 @@ -var structVec=(()=>{var T=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)T(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&T(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(T({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,C=["f32","i32","char","bool"],v=class{constructor(e=15,t){try{let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this,0)}catch(n){throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${n}`)}}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,u=r*n;return l.copyWithin(0,a,u),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){try{let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}catch(t){throw console.error("Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation",t),t}}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,u=c*s,d=s,y=a+d,f=y;for(this._length=o;fs)try{let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,u=new N(a),d=new M(u);d.set(this._f32Memory),this.replaceMemory(d),this._capacity=c}catch(o){throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${o}`)}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let u=r;un.length){let u=r+n.length;for(let x=r;x=s?this:(this._f32Memory=this.shrinkCapacity(r),this._capacity=r,this)}catch(t){throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${t}`)}}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this,0);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${f?", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor":""}} from ${x}`,D="CursorConstructor"+g,P=f?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=f?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` +var structVec=(()=>{var A=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)A(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&A(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(A({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,C=["f32","i32","char","bool"],v=class{constructor(e=15,t){let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this,0)}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,f=r*n;return l.copyWithin(0,a,f),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,f=c*s,d=s,y=a+d,u=y;for(this._length=o;us){let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,f=new N(a),d=new M(f);d.set(this._f32Memory),this.replaceMemory(d),this._capacity=c}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let f=r;fn.length){let f=r+n.length;for(let x=r;x=n?this:(this._f32Memory=this.shrinkCapacity(i),this._capacity=i,this)}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this,0);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${u?", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor":""}} from ${x}`,D="CursorConstructor"+g,P=u?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=u?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` ${n!=="none"?z:""} -${f||r?"":`/** +${u||r?"":`/** * @extends {Vec${g}} */`} -${i==="named"?"export ":""}class ${s} extends Vec${f?g:""} { - static ${f?"readonly ":""}def${f?": StructDef":""} = ${y} - static ${f?"readonly ":""}elementSize${f?": number":""} = ${o} - ${f?"protected ":""}static Cursor = class ${s}Cursor { - ${f?`_viewingIndex: number +${i==="named"?"export ":""}class ${s} extends Vec${u?g:""} { + static ${u?"readonly ":""}def${u?": StructDef":""} = ${y} + static ${u?"readonly ":""}elementSize${u?": number":""} = ${o} + ${u?"protected ":""}static Cursor = class ${s}Cursor { + ${u?`_viewingIndex: number self: Vec${g}`:""} - constructor(self${f?": Vec"+g:""}, index${f?": number":""}) { this.self = self;this._viewingIndex = index} - ${l.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${P}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` + constructor(self${u?": Vec"+g:""}, index${u?": number":""}) { this.self = self;this._viewingIndex = index} + ${l.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${P}[this._viewingIndex${$}]`,p=u?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${d.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` + ${d.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=u?": number":"",E=`get ${m}()${p} { return ${w} }`,S=`set ${m}(newValue${p}) { ${w} = newValue }`;return`${E}; ${S};`}).join(` `)} - ${u.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=f?": string":"",E=`get ${m}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${m}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${E}; ${S};`}).join(` + ${f.map(({field:m,offset:_})=>{let $=_<1?"":" + "+_.toString(),w=`${V}[this._viewingIndex${$}]`,p=u?": string":"",E=`get ${m}()${p} { return String.fromCodePoint(${w} || ${32}) }`,S=`set ${m}(newValue${p}) { ${w} = newValue.codePointAt(0) || ${32} }`;return`${E}; ${S};`}).join(` `)} - ${a.map(({field:m,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,E=~p,S=f?": boolean":"",Y=f?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",A=`${V}[this._viewingIndex${w}]`,J=`get ${m}()${S} { return Boolean(${A} & ${p}) }`,q=`set ${m}(newValue${S}) { ${A} &= ${E};${A} |= ${Y}${$<1?"":" << "+$.toString()}}`;return`${J}; ${q};`}).join(` + ${a.map(({field:m,offset:_,byteOffset:$})=>{let w=_<1?"":" + "+_.toString(),p=1<<$,E=~p,S=u?": boolean":"",Y=u?"(Boolean(newValue) as unknown as number)":"Boolean(newValue)",T=`${V}[this._viewingIndex${w}]`,J=`get ${m}()${S} { return Boolean(${T} & ${p}) }`,q=`set ${m}(newValue${S}) { ${T} &= ${E};${T} |= ${Y}${$<1?"":" << "+$.toString()}}`;return`${J}; ${q};`}).join(` `)} - set e({${c.map(m=>m).join(", ")}}${f?": Struct"+g:""}) { ${c.map(m=>"this."+m+" = "+m).join(";")}; } - get e()${f?": Struct"+g:""} { return {${c.map(m=>m+": this."+m).join(", ")}} } - get ref()${f?`: VecCursor${g}`:""} { return new ${s}.Cursor(this.self, this._viewingIndex) } - index(index${f?": number":""})${f?`: DetachedVecCursor${g}`:""} { this._viewingIndex = index * this.self.elementSize; return this } - }${f?" as "+D:""} - get elementSize()${f?": number":""} { return ${o} } - get def()${f?": StructDef":""} { return ${y} } - ${f?"protected ":""}get cursorDef()${f?": "+D:""} { return ${s}.Cursor } + set e({${c.map(m=>m).join(", ")}}${u?": Struct"+g:""}) { ${c.map(m=>"this."+m+" = "+m).join(";")}; } + get e()${u?": Struct"+g:""} { return {${c.map(m=>m+": this."+m).join(", ")}} } + get ref()${u?`: VecCursor${g}`:""} { return new ${s}.Cursor(this.self, this._viewingIndex) } + index(index${u?": number":""})${u?`: DetachedVecCursor${g}`:""} { this._viewingIndex = index * this.self.elementSize; return this } + }${u?" as "+D:""} + get elementSize()${u?": number":""} { return ${o} } + get def()${u?": StructDef":""} { return ${y} } + ${u?"protected ":""}get cursorDef()${u?": "+D:""} { return ${s}.Cursor } } ${i==="default"?`export default {${s}}`:""} diff --git a/dist/core.d.ts.map b/dist/core.d.ts.map index 5ba13ff..801d5cf 100644 --- a/dist/core.d.ts.map +++ b/dist/core.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;GAEG;AAYH,0BAAkB,QAAQ;IACtB,QAAQ,KAAK;IACb,qBAAqB,KAAK;IAC1B,sBAAsB,KAAK;CAC9B;AAKD,eAAO,MAAM,yBAAyB,yCAK5B,CAAA;AAEV;;;;;;;;;;;;;;;;;;;;GAoBG;AACF,qBAAa,GAAG,CAAC,CAAC,SAAS,SAAS;IACjC;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAK;IAEnC;;;;;;;;;;OAUG;IACH,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAI;IAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAuCE;IACH,MAAM,CAAC,KAAK,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO;IAIrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+CG;IACH,MAAM,CAAC,UAAU,CAAC,CAAC,SAAS,SAAS,EACjC,MAAM,EAAE,kBAAkB,GAC3B,GAAG,CAAC,CAAC,CAAC;IAIT;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,MAAM,CAAC,SAAS,CAAC,CAAC,SAAS,SAAS,EAChC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GACzB,GAAG,CAAC,CAAC,CAAC;IAMT;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,MAAM,CAAC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,IAAI,CAClD,CAAC,MAAM,OAAO,CAAC,GACb,CAAC,CACH,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAC/B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KACR,OAAO,CAAC,CAChB,CAAA;AACD,oBAAY,cAAc,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,IAAI,CACjD,CAAC,MAAM,CAAC,CAAC,GACP,CAAC,CACC,aAAa,EAAE,CAAC,EAChB,YAAY,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EACpC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KACZ,CAAC,CAAC,CACV,CAAA"} \ No newline at end of file diff --git a/dist/core.js b/dist/core.js index 0d8e748..dcf2898 100644 --- a/dist/core.js +++ b/dist/core.js @@ -52,28 +52,23 @@ class Vec { * ``` */ constructor(initialCapacity = 15 /* capacity */, memory) { - try { - let vecCapacity = 0; - let vecLength = 0; - let buffer; - if (!memory) { - vecCapacity = Math.abs(initialCapacity); - buffer = this.createMemory(vecCapacity); - } - else { - vecLength = memory[memory.length - 1 /* lengthReverseIndex */]; - vecCapacity = memory[memory.length - 2 /* capacityReverseIndex */]; - buffer = memory.buffer; - } - this._f32Memory = new Float32Array(buffer); - this._i32Memory = new Int32Array(buffer); - this._length = vecLength; - this._capacity = vecCapacity; - this._cursor = new this.cursorDef(this, 0); + let vecCapacity = 0; + let vecLength = 0; + let buffer; + if (!memory) { + vecCapacity = Math.abs(initialCapacity); + buffer = this.createMemory(vecCapacity); } - catch (err) { - throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`); + else { + vecLength = memory[memory.length - 1 /* lengthReverseIndex */]; + vecCapacity = memory[memory.length - 2 /* capacityReverseIndex */]; + buffer = memory.buffer; } + this._f32Memory = new Float32Array(buffer); + this._i32Memory = new Int32Array(buffer); + this._length = vecLength; + this._capacity = vecCapacity; + this._cursor = new this.cursorDef(this, 0); } /** * Checks if input is a of Vec type. @@ -1314,30 +1309,24 @@ class Vec { * ``` */ reserve(additional) { - try { - const elementSize = this.elementSize; - const length = this._length; - const capacity = this._capacity; - if (length + additional <= capacity) { - return; - } - const newCapacity = length + additional; - const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity); - const bufferSize = (8 /* encodingBytes */ - + elementsMemory); - const buffer = new BUFFER_TYPE(bufferSize); - const memory = new MEMORY_LAYOUT(buffer); - memory.set(this._f32Memory); - this.replaceMemory(memory); - this._capacity = newCapacity; - return this; - } - catch (err) { - console.error(`Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation`, err); - throw err; + const elementSize = this.elementSize; + const length = this._length; + const capacity = this._capacity; + if (length + additional <= capacity) { + return; } + const newCapacity = length + additional; + const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity); + const bufferSize = (8 /* encodingBytes */ + + elementsMemory); + const buffer = new BUFFER_TYPE(bufferSize); + const memory = new MEMORY_LAYOUT(buffer); + memory.set(this._f32Memory); + this.replaceMemory(memory); + this._capacity = newCapacity; + return this; } /** * Reverses an vec in place. The first vec @@ -1627,25 +1616,20 @@ class Vec { const capacity = this._capacity; const minimumCapcity = length + structs.length; if (minimumCapcity > capacity) { - try { - const targetCapacity = capacity * 2; - const newCapacity = minimumCapcity > targetCapacity - ? minimumCapcity + 15 /* capacity */ - : targetCapacity; - const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity); - const bufferSize = (8 /* encodingBytes */ - + elementsMemory); - const buffer = new BUFFER_TYPE(bufferSize); - const memory = new MEMORY_LAYOUT(buffer); - memory.set(this._f32Memory); - this.replaceMemory(memory); - this._capacity = newCapacity; - } - catch (err) { - throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${err}`); - } + const targetCapacity = capacity * 2; + const newCapacity = minimumCapcity > targetCapacity + ? minimumCapcity + 15 /* capacity */ + : targetCapacity; + const elementsMemory = (MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity); + const bufferSize = (8 /* encodingBytes */ + + elementsMemory); + const buffer = new BUFFER_TYPE(bufferSize); + const memory = new MEMORY_LAYOUT(buffer); + memory.set(this._f32Memory); + this.replaceMemory(memory); + this._capacity = newCapacity; } const previousIndex = this._cursor._viewingIndex; for (let i = 0; i < structs.length; i += 1) { @@ -1970,24 +1954,18 @@ class Vec { * ``` */ shrinkTo(minCapacity = 15 /* capacity */) { - try { - const elementSize = this.elementSize; - const length = this._length; - const capacity = this._capacity; - const minCapacityNormalize = minCapacity < 0 - ? 0 - : minCapacity; - const newCapacity = length + minCapacityNormalize; - if (newCapacity >= capacity) { - return this; - } - this._f32Memory = this.shrinkCapacity(newCapacity); - this._capacity = newCapacity; + const length = this._length; + const capacity = this._capacity; + const minCapacityNormalize = minCapacity < 0 + ? 0 + : minCapacity; + const newCapacity = length + minCapacityNormalize; + if (newCapacity >= capacity) { return this; } - catch (err) { - throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${err}`); - } + this._f32Memory = this.shrinkCapacity(newCapacity); + this._capacity = newCapacity; + return this; } /** * Sorts the elements of an array in place and diff --git a/package.json b/package.json index 477aa8f..b04bc1d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "struct-vec", - "version": "0.1.1", + "version": "0.1.2", "description": "Javascript array-like data structures designed for multithreading", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/core.ts b/src/core.ts index d117f9f..79623c5 100644 --- a/src/core.ts +++ b/src/core.ts @@ -282,26 +282,22 @@ export const VALID_DATA_TYPES_INTERNAL = [ initialCapacity: number = defaults.capacity, memory?: ReadonlyInt32Array ) { - try { - let vecCapacity = 0 - let vecLength = 0 - let buffer: SharedArrayBuffer - if (!memory) { - vecCapacity = Math.abs(initialCapacity) - buffer = this.createMemory(vecCapacity) - } else { - vecLength = memory[memory.length - encoding.lengthReverseIndex] - vecCapacity = memory[memory.length - encoding.capacityReverseIndex] - buffer = memory.buffer as SharedArrayBuffer - } - this._f32Memory = new Float32Array(buffer) - this._i32Memory = new Int32Array(buffer) - this._length = vecLength - this._capacity = vecCapacity - this._cursor = new this.cursorDef(this, 0) - } catch (err) { - throw new Error(`[Vec::allocator] buffer memory failed to initialize. ${err}`) + let vecCapacity = 0 + let vecLength = 0 + let buffer: SharedArrayBuffer + if (!memory) { + vecCapacity = Math.abs(initialCapacity) + buffer = this.createMemory(vecCapacity) + } else { + vecLength = memory[memory.length - encoding.lengthReverseIndex] + vecCapacity = memory[memory.length - encoding.capacityReverseIndex] + buffer = memory.buffer as SharedArrayBuffer } + this._f32Memory = new Float32Array(buffer) + this._i32Memory = new Int32Array(buffer) + this._length = vecLength + this._capacity = vecCapacity + this._cursor = new this.cursorDef(this, 0) } /** @@ -1430,33 +1426,28 @@ export const VALID_DATA_TYPES_INTERNAL = [ * ``` */ reserve(additional: number) { - try { - const elementSize = this.elementSize - const length = this._length - const capacity = this._capacity - if (length + additional <= capacity) { - return - } - const newCapacity = length + additional - const elementsMemory = ( - MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity - ) - const bufferSize = ( - encoding.encodingBytes - + elementsMemory - ) - const buffer = new BUFFER_TYPE(bufferSize) - const memory = new MEMORY_LAYOUT(buffer) - memory.set(this._f32Memory) - this.replaceMemory(memory) - this._capacity = newCapacity - return this - } catch (err) { - console.error(`Vec ::allocator: runtime failed to allocate more memory for vec. Aborting operation`, err) - throw err + const elementSize = this.elementSize + const length = this._length + const capacity = this._capacity + if (length + additional <= capacity) { + return } + const newCapacity = length + additional + const elementsMemory = ( + MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity + ) + const bufferSize = ( + encoding.encodingBytes + + elementsMemory + ) + const buffer = new BUFFER_TYPE(bufferSize) + const memory = new MEMORY_LAYOUT(buffer) + memory.set(this._f32Memory) + this.replaceMemory(memory) + this._capacity = newCapacity + return this } /** @@ -1784,28 +1775,24 @@ export const VALID_DATA_TYPES_INTERNAL = [ const capacity = this._capacity const minimumCapcity = length + structs.length if (minimumCapcity > capacity) { - try { - const targetCapacity = capacity * 2 - const newCapacity = minimumCapcity > targetCapacity - ? minimumCapcity + defaults.capacity - : targetCapacity - const elementsMemory = ( - MEMORY_LAYOUT.BYTES_PER_ELEMENT - * elementSize - * newCapacity - ) - const bufferSize = ( - encoding.encodingBytes - + elementsMemory - ) - const buffer = new BUFFER_TYPE(bufferSize) - const memory = new MEMORY_LAYOUT(buffer) - memory.set(this._f32Memory) - this.replaceMemory(memory) - this._capacity = newCapacity - } catch (err) { - throw new Error(`[Vec::allocator] runtime failed to allocate more memory for vec. ${err}`) - } + const targetCapacity = capacity * 2 + const newCapacity = minimumCapcity > targetCapacity + ? minimumCapcity + defaults.capacity + : targetCapacity + const elementsMemory = ( + MEMORY_LAYOUT.BYTES_PER_ELEMENT + * elementSize + * newCapacity + ) + const bufferSize = ( + encoding.encodingBytes + + elementsMemory + ) + const buffer = new BUFFER_TYPE(bufferSize) + const memory = new MEMORY_LAYOUT(buffer) + memory.set(this._f32Memory) + this.replaceMemory(memory) + this._capacity = newCapacity } const previousIndex = this._cursor._viewingIndex for (let i = 0; i < structs.length; i += 1) { @@ -2162,23 +2149,18 @@ export const VALID_DATA_TYPES_INTERNAL = [ shrinkTo( minCapacity: number = defaults.capacity ): Vec { - try { - const elementSize = this.elementSize - const length = this._length - const capacity = this._capacity - const minCapacityNormalize = minCapacity < 0 - ? 0 - : minCapacity - const newCapacity = length + minCapacityNormalize - if (newCapacity >= capacity) { - return this - } - this._f32Memory = this.shrinkCapacity(newCapacity) - this._capacity = newCapacity + const length = this._length + const capacity = this._capacity + const minCapacityNormalize = minCapacity < 0 + ? 0 + : minCapacity + const newCapacity = length + minCapacityNormalize + if (newCapacity >= capacity) { return this - } catch (err) { - throw new Error(`[Vec::allocator] runtime failed to deallocate memory for vec. ${err}`) } + this._f32Memory = this.shrinkCapacity(newCapacity) + this._capacity = newCapacity + return this } /** From 2fe5d7120c693739769f1e27d2e2770a3b962f61 Mon Sep 17 00:00:00 2001 From: mostafa elbannan Date: Sun, 10 Apr 2022 12:57:32 -0700 Subject: [PATCH 4/5] updated readme to include info on references --- README.md | 300 +++++++++++++++-------------- benchmarks/public/dist/compiler.js | 2 +- buildInfo/index.js.br | Bin 4904 -> 4910 bytes dist-deno/compiler.ts | 2 +- dist-web/index.js | 2 +- dist/compiler.js | 2 +- src/compiler.ts | 2 +- src/tests/naming.test.ts | 3 + 8 files changed, 161 insertions(+), 152 deletions(-) diff --git a/README.md b/README.md index 6e29b84..1137a4d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,9 @@ Efficiently communicating between js workers is a pain because you are forced either to pass data by [structured cloning](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) or represent your data as raw buffers. Structured cloning isn't ideal for performance because it requires de-serialization/serialization every time you pass a message, and raw buffers aren't ideal for productivity because they are esoteric and hard to work with. -This package attempts to solve this problem by allowing you to define data structures called `Vecs`. `Vecs` provide an API is similar to javascript `Arrays`, but are completely backed by `SharedArrayBuffers` - thus can be passed between workers at zero-cost, while still being intuitive to work with with. +This package attempts to solve this problem by allowing you to define data structures called `Vecs`. `Vecs` provide an API is similar to javascript `Arrays`, but are completely backed by `SharedArrayBuffers` - thus can be passed between workers at zero-cost, while still being intuitive to work with with. + +This package was inspired by [Google's FlatBuffers](https://google.github.io/flatbuffers/), [Rust's std::Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html), and [@bnaya/objectbuffer](https://github.com/Bnaya/objectbuffer) package. ## Table of Contents @@ -39,7 +41,6 @@ This package attempts to solve this problem by allowing you to define data struc - [Build-time Compiler](#build-time-compiler) - [Caveats](#caveats) - [Indexing does not Return Element](#indexing-does-not-return-element) - - [Elements of a Vec are not Reference Types](#elements-of-a-vec-are-not-reference-types) - [Indexing out of Bounds](#indexing-out-of-bounds) - [Do Not Mutate Vec Length or Capacity during Multithreading](#do-not-mutate-vec-length-or-capacity-during-multithreading) - [Performance Tips](#performance-tips) @@ -64,6 +65,10 @@ This package attempts to solve this problem by allowing you to define data struc ### Quick Start +```bash +npm i struct-vec +``` + ```js import {vec} from "struct-vec" @@ -97,6 +102,9 @@ positions.forEach(pos => { console.log(pos.e) // output: {x: 1, y: 1, z: 1} }) +// get a reference to an index +const firstElement = positions.index(0).ref + // remove elements const allElements = positions.length for (let i = 0; i < allElements; i++) { @@ -130,42 +138,42 @@ console.log(fromMemory.capacity) // output: 15_000 ### Indexing -Indexing into a vec (using the `index` method) is similar to calling `next` method on an iterator. Calling `myVec.index(0)` takes you to the first element but [doesn't actually return the element](#indexing-does-not-return-element). - -If none of that makes sense just remember this, whenever you wish to operate on an element in a vec (get the value or set it), reference a specific field of the element NOT the entire element. +Whenever you wish to operate on an element in a vec (get the value or set it), reference a specific field of the element [NOT the entire element](#indexing-does-not-return-element). #### Getting Values at an Index -If you want the value of an element, refer to one of it's fields (`yourElement.x` for example) or reference the `e` field to get the entire element [by value](#elements-of-a-vec-are-not-reference-types) ([The `e` field is is auto-generated](#default-struct-fields) for all struct defs). +If you want the value of an element, refer to one of it's fields (`yourElement.x` for example), the `e` field to get the entire element [by value](#default_struct_field_e), or the `ref` field to get a [reference](#default_struct_field_ref) ([The `e` and `ref` fields are auto-generated](#default-struct-fields) for all struct defs). ```js import {vec} from "struct-vec" const PositionV = vec({x: "f32", y: "f32", z: "f32"}) const positions = new PositionV() - positions.push({x: 1, y: 2, z: 3}) // 🛑 "wrongValue" doesn't equal {x: 1, y: 2, z: 3} const wrongValue = positions.index(0) -// ✅ "correctValue" equals {x: 1, y: 2, z: 3} -const correctValue = positions.index(0).e -// ✅ "xValue" equals 1 -const xValue = positions.index(0).x -// ✅ "yValue" equals 2 -const yValue = positions.index(0).y -// ✅ "zValue" equals 3 -const zValue = positions.index(0).z -// ✅ also works +// ✅ refer to one the fields const {x, y, z} = positions.index(0) +console.log(x, y, z) // output: 1 2 3 + +// ✅ get entire element by value +const correctValue = positions.index(0).e +console.log(correctValue) // output: {x: 1, y: 2, z: 3} + +// ✅ get a reference to index +const first = positions.index(0).ref +console.log(first.x, first.y, first.z) // output: 1 2 3 + // ✅ array destructuring is allowed as well const [element] = positions +console.log(element) // output: {x: 1, y: 2, z: 3} ``` #### Setting Values at an Index -If you want to set the value of an element, refer to one of it's fields (`yourElement.x = 2` for example) or reference the `e` field to set the entire element([The `e` field is is auto-generated](#default-struct-fields) for all struct defs). +If you want to set the value of an element, refer to one of it's fields (`yourElement.x = 2` for example) or reference the [`e` field](#default_struct_field_e) to set the entire element ([The `e` field is auto-generated](#default-struct-fields) for all struct defs). Both these methods work for [references](#default_struct_field_ref) as well. ```js import {vec} from "struct-vec" @@ -187,19 +195,38 @@ cats.push({ cats.index(0) = { cuteness: 2_876, isDangerous: true, - emoji: "😸" + emoji: "🐆" } -// ✅ works +// ✅ refer to one the fields +cats.index(0).cuteness = 2_876 +cats.index(0).isDangerous = true +cats.index(0).emoji = "🐆" +const {cuteness, emoji, isDangerous} = cats.index(0) +console.log(cuteness, emoji, isDangerous) // output: 2876 true 🐆 + +// ✅ set entire element at once cats.index(0).e = { cuteness: 2_876, isDangerous: true, - emoji: "😸" + emoji: "🐆" } -// ✅ this is fine as well -cats.index(0).cuteness = 2_876 -cats.index(0).isDangerous = true -cats.index(0).emoji = "😸" +console.log(cats.index(0).e) // output: {cuteness: 2_876, isDangerous: true, emoji: "🐆"} + +// ✅ works for references as well +const first = cats.index(0).ref + +first.cuteness = 2_876 +first.isDangerous = true +first.emoji = "🐆" +console.log(first.cuteness, first.emoji, first.isDangerous) // output: 2876 true 🐆 + +first.e = { + cuteness: 2_876, + isDangerous: true, + emoji: "🐆" +} +console.log(first.e) // output: {cuteness: 2_876, isDangerous: true, emoji: "🐆"} ``` ### Adding Elements @@ -269,6 +296,34 @@ for (const element of positions) { } ``` +#### Nested Loops + +Due to some limitations, vecs usually [can only point to one element at a time](#indexing-does-not-return-element). To overcome this we can use a [`detachedCursor`](#indexing-does-not-return-element) or a [`ref`](#default_struct_field_ref). + +```js +import {vec} from "struct-vec" + +const PositionV = vec({x: "f32", y: "f32", z: "f32"}) +const positions = new PositionV(5).fill({x: 1, y: 1, z: 1}) + +// create a cursor initially pointing at index 0 +const innnerCursor = positions.detachedCursor(0) +for (let i = 0; i < positions.length; i++) { + const outerEl = positions.index(i) + for (let x = 0; x < vec.length; x++) { + const innerEl = extraCursor.index(x) + + if (innerEl.x === outerEl.x) { + console.log("same x") + } else if (innerEl.y === outerEl.y) { + console.log("same y") + } else if (innerEl.z === outerEl.z) { + console.log("same z") + } + } +} +``` + ### Removing Elements #### End of Vec @@ -473,7 +528,11 @@ const monsterDef = {isScary: "bool", power: "i32"} Every struct, regardless of definition has some auto-generated fields. Auto-generated fields are: -`e` : this field allows you to get and set an entire element at once. + + +`e` : allows you to get and set an entire element. +- calling `.e` on an element returns the element by value not by reference. [See `ref`](#default_struct_field_e) to get element by reference. + ```js import {vec} from "struct-vec" @@ -501,6 +560,35 @@ cats.index(0).e = { console.log(cats.index(0).e) // output: {cuteness: 2_876, isDangerous: true, emoji: "🐈‍⬛"} ``` + + +`ref`: returns a reference to an index in a vec. +- these references refer to an index in a vec NOT the element at the index. Meaning that if the underlying element is moved, the reference will not longer point to it and potentially [dangle](https://practice.geeksforgeeks.org/problems/what-is-dangling-reference). + +```js +import {vec} from "struct-vec" + +const Enemy = vec({power: "i32", isDead: "bool"}) +const orcs = new Enemy() +orcs.push( + {power: 55, isDead: false}, + {power: 13, isDead: false}, + {power: 72, isDead: false}, +) +// get a reference to index 0 +const firstElement = orcs.index(0).ref +console.log(orcs.index(2).e) // output: {power: 72, isDead: false}, +console.log(firstElement.e) // output: {power: 55, isDead: false} + +// if underlying element of a ref moves +// it does not move with it +orcs.swap(0, 1) +console.log(firstElement.e) // output: {power: 13, isDead: false} + +// ✅ references can create other references +const firstElementRef = firstElement.ref +``` + ### Data types #### f32 @@ -552,11 +640,11 @@ console.log(v.index(0).num) // output: 2 [![access-speed-num](https://img.shields.io/badge/%F0%9F%9A%80%20Access%20Speed-Great-brightgreen)](https://shields.io/) -This data type very fast in terms of access speed as it maps exactly to a native javascript type. +[same as f32](#f32) [![type-safety-num](https://img.shields.io/badge/%F0%9F%AA%B2%20Type%20Saftey-info-blue)](https://shields.io/) -If one sets a `i32` field with an incorrect type (`String` type for example), the field will be set to `NaN`. There a couple of exceptions to this rule, such as if the incorrect type is `null`, an `Array`, a `BigInt`, a `Symbol`, or a `Boolean` which will either throw a runtime error, set the field to 0 or 1, depending on the type and javascript engine. +[same as f32](#f32) #### bool @@ -587,7 +675,7 @@ When a `bool` field is set with an incorrect type (`Number` type for example), t #### char -One valid [unicode 14.0.0](http://www.unicode.org/versions/Unicode14.0.0/) character, takes 8 bytes (64 bits). The `char` type is NOT the same as the javascript's `String` type, as the `char` type is restricted to exactly one character. +One valid [unicode 14.0.0](http://www.unicode.org/versions/Unicode14.0.0/) character, takes 4 bytes (32 bits). Same as javascript's `String` type, except that it is restricted to exactly one character. To define a `char` field: ```js @@ -604,7 +692,7 @@ console.log(v.index(0).char) // output: "a" [![access-speed-char](https://img.shields.io/badge/%F0%9F%9A%80%20Access%20Speed-Bad-yellow)](https://shields.io/) -This data type requires a medium level conversion in order to access. Performance varies wildly between different javascript environments, but you can expect access times for `char` types to be up to 100% slower (2x slower) than the `i32` (or `f32`) type. +This data type requires a medium level conversion in order to access. Can be up to 100% slower (2x slower) than the [`f32`](#f32) type. [![type-safety-char](https://img.shields.io/badge/%F0%9F%AA%B2%20Type%20Saftey-info-blue)](https://shields.io/) @@ -614,12 +702,7 @@ When a `char` field is set with an incorrect type an error will be thrown. If th Struct field names follow the same naming convention as [javascript variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables), excluding unicode characters. -Fields also cannot be named (reserved field names): -- `e` -- `_viewingIndex` -- `ref` -- `isNull` -- `self` +Fields also cannot be named `e`, `_viewingIndex`, `ref`,`index`, `self`. ```js import {vec} from "struct-vec" @@ -643,7 +726,7 @@ const v10 = vec({my$_crazy0_fieldName123: "bool"}) ## Compilers -This package gives you two ways to define vecs, either through the exported `vec` (runtime compiler) or `vecCompile` (build-time compiler) functions. Both compilers emit the exact same vec classes. +This package provides two ways to define vecs, either through the exported `vec` (runtime compiler) or `vecCompile` (build-time compiler) functions. Both compilers emit the exact same vec classes. The key differences between the compilers is that the build-time compiler returns a string containing your vec class which you can write to disk to use in another application, instead of creating a vec class which can be used right away. @@ -665,7 +748,7 @@ Also, if you want a build tool like Webpack, ESBuild, Vite, etc. to apply transf ### Build-time Compiler -The build-time compiler is almost exactly the same as the runtime one. The difference being, after the compiler takes your [struct def](#struct-definitions), it returns a string version of your vec class, instead of a vec class that can be immediately used by javascript. +The build-time compiler is almost exactly the same as the runtime one. The difference being, after the compiler takes your [struct def](#struct-definitions), it returns a string version of your vec class, instead of a vec class that can be immediately used. Here's an example: @@ -727,82 +810,21 @@ export class MyClass extends Vec { get cursorDef() { return MyClass.Cursor } } ``` -You can now import `MyClass` into a javascript or typescript file and it will work just like any other vec. - -There are also other build options, such as generating the typescript version of a class, exporting via `export default`, etc. which I will leave to the [API Reference](#api-reference) to explain. +You can now import `MyClass` into a javascript or typescript file and it will work just like any other vec. Other build options are found in the [API Reference](#api-reference). -Unfortunately, the build-time compiler does not come with a command-line tool - so you'll need to figure out exactly how you want to generate and store your vec classes. +Unfortunately the build-time compiler does not come with a command-line tool - so you'll need to figure out how you want to generate and store your vec classes. ## Caveats ### Indexing does NOT Return Element -> Indexing into a vec (calling ".index") is similar to calling ".next" on an iterator. Calling myVec.index(0) takes you to the first element but doesn't actually return the element. +Indexing into a vec (calling `index`) is similar to calling [`next` on an iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#iterators). Calling `myVec.index(0)` will take you to the first element, allowing you to access it's fields, but does not return the element. -The implication of this is that a vec can only point to one value at a time. In essence the `index` method takes you where the element "lives" and gives you tools to access it's fields, but does NOT return the element. +To get an element by value use the [`e` field](#default_struct_field_e). To get an entire element by reference use the [`ref` field](#default_struct_field_ref). -If you want to operate on the entire element use the `e` field, that comes [built-in with all structs](#default-struct-fields) regardless of their definition. Please note that the `e` field returns the element [by value and NOT by reference](#elements-of-a-vec-are-not-reference-types). +The implication of all this, is that a vec can only point to one element at a time. If you want to look at two or more elements at once, you will have to create additional cursors, which can created with the `Vec.detachedCursor` method. -Generally this is a non-issue, but it can cause bugs in situations like these: - -```js -import {vec} from "struct-vec" - -const PositionV = vec({x: "f32", y: "f32", z: "f32"}) -const positions = new PositionV() - -positions.push({x: 1, y: 1, z: 1}) -positions.push({x: 3, y: 3, z: 3}) -positions.push({x: 2, y: 2, z: 2}) - -// 🛑 incorrect example -// point vec to index 0 -const element0 = positions.index(0) -// point vec from 0 to 1 -const element1 = positions.index(1) - -// ❌ uh-oh, since I didn't capture the value of any of -// the indexes in a variable this occurs -console.log(element0.x) // output: 3 -console.log(element1.x) // output: 3 - -// ✅ correct example -// point vec to 0 and capture entire element (by value) -const element0correct = positions.index(0).e -// move vec from 0 to 1 and capture entire element (by value) -const element1correct = positions.index(1).e - -// 👍 works as expected -console.log(element0correct.x) // output: 1 -console.log(element1correct.x) // output: 3 -``` - -or if attempting to swap elements: - -```js -import {vec} from "struct-vec" - -const PositionV = vec({x: "f32", y: "f32", z: "f32"}) -const positions = new PositionV() - -positions.push({x: 1, y: 1, z: 1}) -positions.push({x: 3, y: 3, z: 3}) - -// 🛑 incorrect swap -const tmp = positions.index(0) -positions.index(0) = positions.index(1) // throws Error -positions.index(1) = tmp // throws Error - -// ✅ use the .swap method (most performant) -positions.swap(0, 1) -// ✅ you can manually swap them yourself -// using the "e" field -const correctTmp = positions.index(0).e -positions.index(0).e = positions.index(1).e -positions.index(1).e = correctTmp -``` - -or when attempt to do nested imperative for loops (vec iterators don't have this problem): +An example to illustrate this point is a nested for loop: ```js import {vec} from "struct-vec" @@ -823,58 +845,44 @@ for (let i = 0; i < positions.length; i++) { const innerEl = positions.index(x) } // ❌ vec was moved to index 2 (vec.length) at the - // end of the inner - // loop and is no longer pointing to index i + // end of the inner loop and is no longer + // pointing to index i console.log(el.e) // output: {x: 2, y: 2, z: 2} } -// ✅ correct example +// ✅ Use a detached cursor +// create a cursor initially pointing +// at index 0 +const extraCursor = positions.detachedCursor(0) for (let i = 0; i < positions.length; i++) { - // move vec to index 0 - // capture element in variable - // before inner loop changes index - const el = positions.index(i).e + const el = positions.index(i) + // move extra cursor from index 0 through 2 + for (let x = 0; x < vec.length; x++) { + // detached cursors can be move via the "index" + // method, just like vecs but don't + // influence were the vec is pointing + const innerEl = extraCursor.index(x) + } + console.log(el.e) // output: what ever is at index i +} + +// ✅ Use a reference, also works +// but less efficent +for (let i = 0; i < positions.length; i++) { + // refs are just a special + // type of "detachedCursor" under the hood + const el = positions.index(i).ref // move vec from index 0 through 2 for (let x = 0; x < vec.length; x++) { const innerEl = positions.index(x) } - console.log(el) // output: what ever is at index i + console.log(el.e) // output: what ever is at index i } ``` -### Elements of a Vec are not Reference Types - -Individual elements of a vec are behave like [primitive types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values) (numbers, booleans, etc.) and are not [reference types](https://javascript.info/reference-type), unlike javascript objects which are reference types. If you want to set a particular element, you must index into the vec and change it there. - -```js -import {vec} from "struct-vec" - -const PositionV = vec({x: "f32", y: "f32", z: "f32"}) -const positions = new PositionV() - -positions.push({x: 1, y: 1, z: 1}) - -// vec elements behave like primitives -// so this gets the element by value -const element0 = positions.index(0).e -element0.x = 2 -console.log(element0) // output: {x: 2, y: 1, z: 1} -// 🛑 changes not made to the element in vec -console.log(positions.index(0).e) // output: {x: 1, y: 1, z: 1} - -// you must index into the vec to make changes -positions.index(0).x = 2 -// ✅ changes made -console.log(positions.index(0).e) // output: {x: 2, y: 1, z: 1} -// ✅ also works -const el = positions.index(0) -el.x = 3 -console.log(positions.index(0).e) // output: {x: 3, y: 1, z: 1} -``` - ### Indexing Out of Bounds -Indexing out of bounds negatively (`i < 0`) will return `undefined` just like an array. Indexing out of bounds past the length (`i > vec.length - 1`) may or may not return `undefined`. Sometimes a vec will keep garbage memory at the end to avoid resizing and this is the expected behavior. +Indexing out of bounds negatively (`i < 0`) will return `undefined` just like an `Array`. Indexing out of bounds past the length (`i > vec.length - 1`) may or may not return `undefined`. Sometimes a vec will keep garbage memory at the end to avoid resizing and this is the expected behavior. ```js import {vec} from "struct-vec" @@ -901,7 +909,7 @@ console.log(positions.index(10_000).x) // output: undefined ### Do Not Mutate Vec Length or Capacity during Multithreading -Vecs are designed for multithreaded iterations and NOT multithreaded length-changing (or capacity-changing) mutations. Beyond the fact that mutating the length (or capacity) of a vec during multithreading is a bad idea, it will lead to unpredictable bugs. Do not use any methods that may potentially change the `length` (or `capacity`) of a vec during multithreading. +Do not use any methods that may potentially change the `length` (or `capacity`) of a vec during multi-threading. Doing so will lead to unpredictable bugs. Length-changing methods include: `pop`, `truncate`, `splice`, `shift`, `push`, `fill`, `unshift` @@ -954,7 +962,7 @@ console.log(positions.length) // output: 5_000 ES6 array destructuring operator (`const [element] = vec`), spread operator (`...vec`), and for...of loops (`for (const el of vec)`) should be avoided except if you want to [cast a vec to an array](#casting) or something similar. -These operators force vecs to deserialize their internal binary representation of structs to objects - [which is costly](#es6-iterator-loop) and can cause some unexpected side-effects due to fact that they [return elements by value , NOT by reference](#elements-of-a-vec-are-not-reference-types). +These operators force vecs to deserialize their internal binary representation of structs to objects - [which is costly](#es6-iterator-loop) and can cause some unexpected side-effects due to fact that they return elements by [value](#default_struct_field_e), NOT by reference. NOTE: the `values`, `entries`, `keys` methods are also es6 iterators. @@ -992,8 +1000,6 @@ before recording. [The multithreaded benchmarks](#parallel-loop) are the only ex Test machine was a Windows 11/WSL-Ubuntu 20.04 (x64), with a Intel i7-9750H CPU (12 core), and 16 GB RAM. -All of these tests are micro benchmarks which rarely tell the entire truth about performance, but can give you an idea on what to expect from vecs in terms of performance. - ### Iteration #### Imperative loop diff --git a/benchmarks/public/dist/compiler.js b/benchmarks/public/dist/compiler.js index af8b501..79deda2 100644 --- a/benchmarks/public/dist/compiler.js +++ b/benchmarks/public/dist/compiler.js @@ -21,7 +21,7 @@ function restrictedFieldName(name) { case "e": case "_viewingIndex": case "ref": - case "isNull": + case "index": return true; default: return false; diff --git a/buildInfo/index.js.br b/buildInfo/index.js.br index bbc6af0d5618cee489e893b9afe7fb2d95b1282b..39a1123f6c849b58acb7e93014a9cd502f18315b 100644 GIT binary patch literal 4910 zcmV+}6VdD&z(rA%ZdMCG=YefZd+-B<@l_qT^o$d^;*Izmp1TCC-zzzVHhAJFsfd+W92>$<6EvtJEgu}Q`!ufkYBmvO(^kAx;mqX#CBeJ2-N7fuwN zXB(20(?u!#I){lv`kI_y9UmQ1&ySIz7_#8~N}k<+Gq}93&ir)~Vj*Yu5kI5WvTOD` zcNHm|dcngtbtlF2nnr}EUw55r7q5qq5KkJ>JpsBlTrXmY(m*X=FU0eW{{0ljbBKc=Nj+D zZZ-mkBrGp^2K|dK5Q&TRg*!{Dl3h*nBo|o^r)9gA6JKXMx7Rn7)k{;W`1Ld?@Dq>q zh^5&$Y(|p=g|L3Xd+>Bh7fM;4v%-VEj^^pg&p)HnCbcN8df`1;L4tq<{uWjM7>c+^ zM>Nd#KjgIcozX4*lwKTtY?{F~$Ui)4j+%vB6O}~LJb@xBsqRRJ__N`A7?R6rPABED zq?e%H*vP5rF$Sb%i0he$KT4uS6yv`H4^MI3D&!K9HD&h#z+h1F;X@5HMOj9e=pPm& zpUcG?5;*qm4Y&M3Xx%uwTD%5dem=`WqQq~YF~ad&pk^%>wX1T|N+3oe#EcWo!HF4W z{N#D~N%gvy%EBO|reHp7!4dN|fuQ1uFd8Xr5g0WcD&Qu)qJuW*ApOIvz?O+>FN=!Q z4GUuRgxt*M%$2}y#${p~LCxg&m7=T0ylM?iH@6vZk>Vdv!qdlol~Nc;JGt}TC3cJU zSXSUQiB&(CsZxGZw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W1umcSfi2z)40u%mFsAGc}dQM6_}by1iuER;iRjcvVovEgma7F!>d zD*+OcIwZ;br0*!!U)Zk5PR*wX3}`-zrrY_Y7LB&nrTwR5mp2wBtpk8z61?e-c50DY z_g)0#yt6dT>&wb1xGi`Ha{)__-g9nTQ0!V=KCuVPKXrdu+Vc**Yn4#?*O3-gSu8W% z4tPLC36*?M9-Bvn?L)tTD2%Tq6qB*UViX(TVwembu#^n84Jo&Z9mIhu zjYjLIYcbur1;1qZdwagPYTLd!=sCuRHYW(B>x2=ly0Y|n6#mA$#kFo_tqr^`8E1=& zC|QPi?XN^Wo-$|NAOxdQ-Ga-RAe-sGYo>TN(w@o#GTs4ZCyFopabZQ+ze+RAtAub5 apAy1qyB#fmw$zb(Ef8<%d7*6MbHV_pVSMxe diff --git a/dist-deno/compiler.ts b/dist-deno/compiler.ts index 80749bf..f424c77 100644 --- a/dist-deno/compiler.ts +++ b/dist-deno/compiler.ts @@ -33,7 +33,7 @@ function restrictedFieldName(name: string): boolean { case "e": case "_viewingIndex": case "ref": - case "isNull": + case "index": return true default: return false diff --git a/dist-web/index.js b/dist-web/index.js index 2dece66..3f3b58e 100644 --- a/dist-web/index.js +++ b/dist-web/index.js @@ -1,4 +1,4 @@ -var structVec=(()=>{var A=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)A(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&A(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(A({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,C=["f32","i32","char","bool"],v=class{constructor(e=15,t){let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this,0)}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,f=r*n;return l.copyWithin(0,a,f),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,f=c*s,d=s,y=a+d,u=y;for(this._length=o;us){let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,f=new N(a),d=new M(f);d.set(this._f32Memory),this.replaceMemory(d),this._capacity=c}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let f=r;fn.length){let f=r+n.length;for(let x=r;x=n?this:(this._f32Memory=this.shrinkCapacity(i),this._capacity=i,this)}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this,0);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${u?", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor":""}} from ${x}`,D="CursorConstructor"+g,P=u?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=u?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` +var structVec=(()=>{var A=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(h,e)=>{for(var t in e)A(h,t,{get:e[t],enumerable:!0})},H=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(h,s)&&s!==t&&A(h,s,{get:()=>e[s],enumerable:!(n=G(e,s))||n.enumerable});return h};var K=h=>H(A({},"__esModule",{value:!0}),h);var ie={};Z(ie,{Vec:()=>v,default:()=>se,validateStructDef:()=>j,vec:()=>B,vecCompile:()=>O});var M=Float32Array,N=SharedArrayBuffer,C=["f32","i32","char","bool"],v=class{constructor(e=15,t){let n=0,s=0,i;t?(s=t[t.length-1],n=t[t.length-2],i=t.buffer):(n=Math.abs(e),i=this.createMemory(n)),this._f32Memory=new Float32Array(i),this._i32Memory=new Int32Array(i),this._length=s,this._capacity=n,this._cursor=new this.cursorDef(this,0)}static isVec(e){return e instanceof this}static fromMemory(e){return new this(0,e)}static fromArray(e){let t=new this(e.length+15);return t.push(...e),t}static fromString(e){let t=JSON.parse(e);if(!Array.isArray(t))throw TypeError("inputted string was not a stringified vec");let n=new this(0),s=t[t.length-3];if(s!==n.elementSize)throw TypeError(`Inputted array does not match the encoding for this vec class. Size of element must be ${n.elementSize}, got "${s}" (type=${typeof s})`);let i=t[t.length-1],r=t[t.length-2];if(!Number.isInteger(i)||!Number.isInteger(r))throw TypeError("Inputted length or capacity of vec is not an integer.");n.reserve(r);let o=n._f32Memory;for(let c=0;c-1;s-=1){let i=this.index(s);if(e(i,s,this))return this._cursor._viewingIndex=t,s}return this._cursor._viewingIndex=t,-1}reduce(e,t){if(t===void 0)throw TypeError("Reduce of vec with no initial value. Initial value argument is required.");let n=this._cursor._viewingIndex,s=t,i=this._length;for(let r=0;r-1;r-=1){let o=this.index(r);s=e(s,o,r,this)}return this._cursor._viewingIndex=n,s}every(e){let t=this._cursor._viewingIndex,n=this._length;for(let s=0;s({done:(e+=1)>=t,value:this.index(e).e})}}entries(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:[e,this.index(e).e]})})}}keys(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:e})})}}values(){let e=-1,t=this._length;return{[Symbol.iterator]:()=>({next:()=>({done:(e+=1)>=t,value:this.index(e).e})})}}slice(e=0,t){let n=this.elementSize,s=this._length,i=e<0?s+e:e;if(i<0||i>s-1)return new this.constructor;t=t||this._length;let r=t<0?s+t:t;if(r<0||r>s)return new this.constructor;let o=new this.constructor,c=r-i;if(c<0)return o;let l=this._f32Memory.slice(),a=i*n,f=r*n;return l.copyWithin(0,a,f),o._length=c,o.replaceMemory(l),o.deallocateExcessMemory(),o}copyWithin(e,t=0,n){let s=this.elementSize,i=this._length,r=e<0?i+e:e;if(r<0||r>i-1)return this;let o=t<0?i+t:t;if(o<0||o>i-1)return this;n=n||i;let c=n<0?i+n:n;return c<0||c>i?this:(this._f32Memory.copyWithin(r*s,o*s,c*s),this)}reserve(e){let t=this.elementSize,n=this._length,s=this._capacity;if(n+e<=s)return;let i=n+e,r=M.BYTES_PER_ELEMENT*t*i,o=8+r,c=new N(o),l=new M(c);return l.set(this._f32Memory),this.replaceMemory(l),this._capacity=i,this}reverse(){let e=this.elementSize;if(this._length<2)return this;let n=0,s=this._length-1;this.reserve(1);let i=this._length*e;for(;nthis._length?this._length:e;return this._length-=t,this.deallocateExcessMemory(),this._length}fill(e,t=0,n){let s=this.elementSize,i=this._capacity,r=this._length,o=t<0?r+t:t;o=o<0?0:o>r-1?r:o,n=n||i;let c=n<0?i+n:n;c=c<0?0:c>i?i:c;let l=c-o;if(l<1)return this;if(this.index(o).e=e,l<2)return this;let a=o*s,f=c*s,d=s,y=a+d,u=y;for(this._length=o;us){let o=s*2,c=i>o?i+15:o,l=M.BYTES_PER_ELEMENT*t*c,a=8+l,f=new N(a),d=new M(f);d.set(this._f32Memory),this.replaceMemory(d),this._capacity=c}let r=this._cursor._viewingIndex;for(let o=0;oi-1)return c;let l=i-r;l=l<0?0:l,t=t===void 0?l:t,t=t<1?0:t,t=t>l?l:t;let a=0;if(t===n.length)for(let f=r;fn.length){let f=r+n.length;for(let x=r;x=n?this:(this._f32Memory=this.shrinkCapacity(i),this._capacity=i,this)}sort(e){if(this._length<2)return this;let t=new this.cursorDef(this,0);this.reserve(1);let n=this.elementSize,s=this._length*n;if(this._length===2){if(e(t,this.index(1))!==0){let o=0*n;this._f32Memory.copyWithin(s,o,o+n);let c=1*n;this._f32Memory.copyWithin(o,c,c+n),this._f32Memory.copyWithin(c,s,s+n)}return this}let i=!1;for(;!i;){i=!0;for(let r=0;r({field:l,type:h[l]}));if(e.length<1)throw SyntaxError(`${I} struct definition must have at least one key`);let t=0,n={elementSize:0,fieldNames:[],float32Fields:[],int32Fields:[],booleanFields:[],charFields:[]},s=[],i=[],r=[],o=[];for(let l=0;l`,x=`"${n}"`,z=`import {Vec${u?", StructDef, Struct, CursorConstructor, VecCursor, DetachedVecCursor":""}} from ${x}`,D="CursorConstructor"+g,P=u?"(this.self as unknown as {_f32Memory: Float32Array})._f32Memory":"this.self._f32Memory",V=u?"(this.self as unknown as {_i32Memory: Int32Array})._i32Memory":"this.self._i32Memory";return{className:s,def:` ${n!=="none"?z:""} ${u||r?"":`/** * @extends {Vec${g}} diff --git a/dist/compiler.js b/dist/compiler.js index e5dd805..81427cd 100644 --- a/dist/compiler.js +++ b/dist/compiler.js @@ -26,7 +26,7 @@ function restrictedFieldName(name) { case "e": case "_viewingIndex": case "ref": - case "isNull": + case "index": return true; default: return false; diff --git a/src/compiler.ts b/src/compiler.ts index cad2b3b..f6f814e 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -40,7 +40,7 @@ function restrictedFieldName(name: string): boolean { case "e": case "_viewingIndex": case "ref": - case "isNull": + case "index": return true default: return false diff --git a/src/tests/naming.test.ts b/src/tests/naming.test.ts index f704554..41ee539 100644 --- a/src/tests/naming.test.ts +++ b/src/tests/naming.test.ts @@ -17,6 +17,9 @@ describe("field name restrictions", () => { it("defining structs that include field names which conflict with any of the standard methods or properties throws error", () => { expect(() => {vec({e: "f32"})}).toThrow() expect(() => {vec({self: "f32"})}).toThrow() + expect(() => {vec({ref: "f32"})}).toThrow() + expect(() => {vec({_viewingIndex: "f32"})}).toThrow() + expect(() => {vec({index: "f32"})}).toThrow() }) }) From bf29999bda183975c8c45ec0532172ff6491a095 Mon Sep 17 00:00:00 2001 From: mostafa elbannan Date: Sun, 10 Apr 2022 13:16:41 -0700 Subject: [PATCH 5/5] fixed typos --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1137a4d..f7866a6 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ for (const element of positions) { #### Nested Loops -Due to some limitations, vecs usually [can only point to one element at a time](#indexing-does-not-return-element). To overcome this we can use a [`detachedCursor`](#indexing-does-not-return-element) or a [`ref`](#default_struct_field_ref). +Due to some limitations, vecs usually [can only point to one element at a time](#indexing-does-not-return-element). To overcome a [`detachedCursor`](#indexing-does-not-return-element) or [`ref`](#default_struct_field_ref) can be used. ```js import {vec} from "struct-vec" @@ -563,7 +563,7 @@ console.log(cats.index(0).e) // output: {cuteness: 2_876, isDangerous: true, emo `ref`: returns a reference to an index in a vec. -- these references refer to an index in a vec NOT the element at the index. Meaning that if the underlying element is moved, the reference will not longer point to it and potentially [dangle](https://practice.geeksforgeeks.org/problems/what-is-dangling-reference). +- these references refer to an index in a vec NOT the element at the index. Meaning that if the underlying element is moved, the reference will no longer point to it and potentially [dangle](https://practice.geeksforgeeks.org/problems/what-is-dangling-reference). ```js import {vec} from "struct-vec"