json-as 0.5.52 → 0.5.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,206 @@
1
+ import { bench, blackbox } from "../../../WebAssembly/benchmark-wasm/assembly/bench";
2
+ import { __atoi_fast, snip_fast, unsafeCharCodeAt } from "../assembly/src/util";
3
+ import { JSON } from "../assembly";
4
+ import { backSlashCode, commaCode, eCode, fCode, leftBraceCode, leftBracketCode, nCode, nullWord, quoteCode, rCode, rightBraceCode, rightBracketCode, tCode, trueWord, uCode } from "../assembly/src/chars";
5
+ import { isSpace } from "util/string";
6
+ class Vec3 {
7
+ x: i32;
8
+ y: i32;
9
+ z: i32;
10
+ @inline
11
+ __JSON_Serialize(): string {
12
+ return `{"x":${this.x.toString()},"y":${this.y.toString()},"z":${this.z.toString()}}`;
13
+ }
14
+ @inline
15
+ __JSON_Set_Key(key: string, value: string): void {
16
+ if (key == "x") {
17
+ this.x = ____parseObjectValue<i32>(value);
18
+ return;
19
+ }
20
+ if (key == "y") {
21
+ this.y = ____parseObjectValue<i32>(value);
22
+ return;
23
+ }
24
+ if (key == "z") {
25
+ this.z = ____parseObjectValue<i32>(value);
26
+ return;
27
+ }
28
+ }
29
+ @inline
30
+ __JSON_Deserialize(data: string): Vec3 {
31
+ let schema: nonnull<Vec3> = changetype<nonnull<Vec3>>(
32
+ __new(offsetof<nonnull<Vec3>>(), idof<nonnull<Vec3>>())
33
+ );
34
+ let key = "";
35
+ let isKey = false;
36
+ let depth = 0;
37
+ let outerLoopIndex = 1;
38
+ for (; outerLoopIndex < data.length - 1; outerLoopIndex++) {
39
+ const char = unsafeCharCodeAt(data, outerLoopIndex);
40
+ if (char === leftBracketCode) {
41
+ for (
42
+ let arrayValueIndex = outerLoopIndex;
43
+ arrayValueIndex < data.length - 1;
44
+ arrayValueIndex++
45
+ ) {
46
+ const char = unsafeCharCodeAt(data, arrayValueIndex);
47
+ if (char === leftBracketCode) {
48
+ depth++;
49
+ } else if (char === rightBracketCode) {
50
+ depth--;
51
+ if (depth === 0) {
52
+ ++arrayValueIndex;
53
+ // @ts-ignore
54
+ schema.__JSON_Set_Key(
55
+ key,
56
+ data.slice(outerLoopIndex, arrayValueIndex)
57
+ );
58
+ outerLoopIndex = arrayValueIndex;
59
+ isKey = false;
60
+ break;
61
+ }
62
+ }
63
+ }
64
+ } else if (char === leftBraceCode) {
65
+ for (
66
+ let objectValueIndex = outerLoopIndex;
67
+ objectValueIndex < data.length - 1;
68
+ objectValueIndex++
69
+ ) {
70
+ const char = unsafeCharCodeAt(data, objectValueIndex);
71
+ if (char === leftBraceCode) {
72
+ depth++;
73
+ } else if (char === rightBraceCode) {
74
+ depth--;
75
+ if (depth === 0) {
76
+ ++objectValueIndex;
77
+ // @ts-ignore
78
+ schema.__JSON_Set_Key(
79
+ key,
80
+ data.slice(outerLoopIndex, objectValueIndex)
81
+ );
82
+ outerLoopIndex = objectValueIndex;
83
+ isKey = false;
84
+ break;
85
+ }
86
+ }
87
+ }
88
+ } else if (char === quoteCode) {
89
+ for (
90
+ let stringValueIndex = ++outerLoopIndex;
91
+ stringValueIndex < data.length - 1;
92
+ stringValueIndex++
93
+ ) {
94
+ const char = unsafeCharCodeAt(data, stringValueIndex);
95
+ if (
96
+ char === quoteCode &&
97
+ unsafeCharCodeAt(data, stringValueIndex - 1) !== backSlashCode
98
+ ) {
99
+ if (isKey === false) {
100
+ key = data.slice(outerLoopIndex, stringValueIndex);
101
+ isKey = true;
102
+ } else {
103
+ // @ts-ignore
104
+ schema.__JSON_Set_Key(
105
+ key,
106
+ data.slice(outerLoopIndex, stringValueIndex)
107
+ );
108
+ isKey = false;
109
+ }
110
+ outerLoopIndex = ++stringValueIndex;
111
+ break;
112
+ }
113
+ }
114
+ } else if (char == nCode) {
115
+ // @ts-ignore
116
+ schema.__JSON_Set_Key(key, nullWord);
117
+ isKey = false;
118
+ } else if (
119
+ char === tCode &&
120
+ unsafeCharCodeAt(data, ++outerLoopIndex) === rCode &&
121
+ unsafeCharCodeAt(data, ++outerLoopIndex) === uCode &&
122
+ unsafeCharCodeAt(data, ++outerLoopIndex) === eCode
123
+ ) {
124
+ // @ts-ignore
125
+ schema.__JSON_Set_Key(key, trueWord);
126
+ isKey = false;
127
+ } else if (
128
+ char === fCode &&
129
+ unsafeCharCodeAt(data, ++outerLoopIndex) === "a".charCodeAt(0) &&
130
+ unsafeCharCodeAt(data, ++outerLoopIndex) === "l".charCodeAt(0) &&
131
+ unsafeCharCodeAt(data, ++outerLoopIndex) === "s".charCodeAt(0) &&
132
+ unsafeCharCodeAt(data, ++outerLoopIndex) === eCode
133
+ ) {
134
+ // @ts-ignore
135
+ schema.__JSON_Set_Key(key, "false");
136
+ isKey = false;
137
+ } else if ((char >= 48 && char <= 57) || char === 45) {
138
+ let numberValueIndex = ++outerLoopIndex;
139
+ for (; numberValueIndex < data.length; numberValueIndex++) {
140
+ const char = unsafeCharCodeAt(data, numberValueIndex);
141
+ if (char === commaCode || char === rightBraceCode || isSpace(char)) {
142
+ // @ts-ignore
143
+ schema.__JSON_Set_Key(
144
+ key,
145
+ data.slice(outerLoopIndex - 1, numberValueIndex)
146
+ );
147
+ outerLoopIndex = numberValueIndex;
148
+ isKey = false;
149
+ break;
150
+ }
151
+ }
152
+ }
153
+ }
154
+ return schema;
155
+ }
156
+ }
157
+
158
+ const vec: Vec3 = {
159
+ x: 3,
160
+ y: 1,
161
+ z: 8,
162
+ }
163
+ /*
164
+ bench("Parse Number SNIP", () => {
165
+ blackbox<i32>(snip_fast<i32>("12345"));
166
+ });
167
+
168
+ bench("Parse Number ATOI", () => {
169
+ blackbox<i32>(__atoi_fast<i32>("12345"));
170
+ })
171
+
172
+ bench("Parse Number STDLIB", () => {
173
+ blackbox<i32>(i32.parse("12345"));
174
+ });
175
+
176
+ bench("Stringify Object (Vec3)", () => {
177
+ blackbox<string>(vec.__JSON_Serialize());
178
+ });*/
179
+
180
+ bench("Parse Object (Vec3)", () => {
181
+ blackbox<Vec3>(vec.__JSON_Deserialize('{"x":0,"y":0,"z":0}'));
182
+ });
183
+
184
+ bench("Stringify Number Array", () => {
185
+ blackbox<string>(JSON.stringify<i32[]>([1, 2, 3]));
186
+ });
187
+
188
+ bench("Parse Number Array", () => {
189
+ blackbox<i32[]>(JSON.parse<i32[]>(blackbox("[1,2,3]")));
190
+ });
191
+
192
+ bench("Stringify String", () => {
193
+ blackbox<string>(JSON.stringify(blackbox('Hello "World!')));
194
+ });
195
+
196
+ bench("Parse String", () => {
197
+ blackbox<string>(JSON.parse<string>(blackbox('"Hello "World!"')));
198
+ });
199
+
200
+ bench("Stringify Boolean Array", () => {
201
+ blackbox(JSON.stringify<boolean[]>([true, false, true]));
202
+ });
203
+
204
+ bench("Stringify String Array", () => {
205
+ blackbox(JSON.stringify<string[]>(["a", "b", "c"]));
206
+ });
@@ -0,0 +1,99 @@
1
+ {
2
+ "extends": "assemblyscript/std/assembly.json",
3
+ "include": [
4
+ "./**/*.ts"
5
+ ],
6
+ "compilerOptions": {
7
+ /* Visit https://aka.ms/tsconfig to read more about this file */
8
+ /* Projects */
9
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
10
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
11
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
12
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
13
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
14
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
15
+ /* Language and Environment */
16
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
17
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
18
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
19
+ "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
20
+ "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
21
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
22
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
23
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
24
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
25
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
26
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
27
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
28
+ /* Modules */
29
+ "module": "commonjs" /* Specify what module code is generated. */,
30
+ // "rootDir": "./", /* Specify the root folder within your source files. */
31
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
32
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
+ // "resolveJsonModule": true, /* Enable importing .json files. */
40
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
41
+ /* JavaScript Support */
42
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45
+ /* Emit */
46
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
47
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
48
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
49
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
50
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
51
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
52
+ // "removeComments": true, /* Disable emitting comments. */
53
+ // "noEmit": true, /* Disable emitting files from a compilation. */
54
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
55
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
56
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
57
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
58
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
59
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
61
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
62
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
63
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
64
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
65
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
66
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
67
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
68
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
69
+ /* Interop Constraints */
70
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
73
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
75
+ /* Type Checking */
76
+ "strict": false /* Enable all strict type-checking options. */,
77
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
78
+ "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
79
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
80
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
81
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
82
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
83
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
84
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
85
+ "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
86
+ "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
87
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
88
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
89
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
90
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
91
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
92
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
93
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
94
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
95
+ /* Completeness */
96
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
97
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
98
+ }
99
+ }
@@ -0,0 +1,52 @@
1
+ # Comparison between integer parsing algorithms
2
+
3
+ SNIP: 261M iterations over 5000ms
4
+ ATOI: 285M iterations over 5000ms
5
+
6
+
7
+ ### Log
8
+
9
+ ```
10
+ yarn run v1.22.19
11
+ $ astral -Ospeed --noAssert --uncheckedBehavior always --runtime stub
12
+ Compiling assembly/__benches__/as-json.ts
13
+
14
+ Benchmarking Parse Number SNIP: Warming up for 3000ms
15
+ Benchmarking Parse Number SNIP: Collecting 100 samples in estimated 5000ms (261M iterations)
16
+ Benchmarking Parse Number SNIP: Analyzing
17
+ Parse Number SNIP time: [18.146ns 18.381ns 18.624ns]
18
+ change: [-13.073% -10.614% -8.1347%] (p = 0.00 < 0.05)
19
+ Performance has improved.
20
+ Found 9 outliers among 100 measurements (9%)
21
+ 8 (8%) high mild
22
+ 1 (1%) high severe
23
+
24
+ Benchmarking Parse Number ATOI: Warming up for 3000ms
25
+ Benchmarking Parse Number ATOI: Collecting 100 samples in estimated 5000ms (285M iterations)
26
+ Benchmarking Parse Number ATOI: Analyzing
27
+ Parse Number ATOI time: [16.962ns 17.219ns 17.501ns]
28
+ change: [-3.5659% -0.8496% +2.0516%] (p = 0.00 < 0.05)
29
+ Change within noise threshold.
30
+ Found 7 outliers among 100 measurements (7%)
31
+ 2 (2%) high mild
32
+ 5 (5%) high severe
33
+
34
+ Benchmarking Parse Number STDLIB: Warming up for 3000ms
35
+ Benchmarking Parse Number STDLIB: Collecting 100 samples in estimated 5000ms (176M iterations)
36
+ Benchmarking Parse Number STDLIB: Analyzing
37
+ Parse Number STDLIB time: [28.298ns 28.763ns 29.383ns]
38
+ change: [-3.3724% -1.5367% +0.1796%] (p = 0.00 < 0.05)
39
+ Change within noise threshold.
40
+ Found 5 outliers among 100 measurements (5%)
41
+ 3 (3%) high mild
42
+ 2 (2%) high severe
43
+
44
+ Benchmarking Parse Number OLD: Warming up for 3000ms
45
+ Benchmarking Parse Number OLD: Collecting 100 samples in estimated 5000ms (171M iterations)
46
+ Benchmarking Parse Number OLD: Analyzing
47
+ Parse Number OLD time: [28.888ns 29.341ns 29.804ns]
48
+ change: [-2.123% -0.5458% +1.1939%] (p = 0.00 < 0.05)
49
+ Change within noise threshold.
50
+ Found 3 outliers among 100 measurements (3%)
51
+ 3 (3%) high mild
52
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-as",
3
- "version": "0.5.52",
3
+ "version": "0.5.56",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "types": "assembly/index.ts",
6
6
  "author": "Jairus Tanaka",
@@ -13,32 +13,38 @@
13
13
  ],
14
14
  "license": "MIT",
15
15
  "scripts": {
16
- "aspect": "asp",
17
- "bench:astral": "astral -Ospeed --noAssert --uncheckedBehavior always --runtime stub",
18
- "build:test": "asc assembly/test.ts --target test",
16
+ "test:aspect": "asp",
17
+ "bench:astral": "astral --optimizeLevel 3 --shrinkLevel 0 --converge --noAssert --uncheckedBehavior never --runtime stub",
18
+ "build:test": "asc assembly/test.ts -o build/test.wasm --transform ./transform/lib/index.js --config ./node_modules/@assemblyscript/wasi-shim/asconfig.json --optimizeLevel 3 --shrinkLevel 0 --noAssert --uncheckedBehavior always --converge --runtime stub",
19
+ "build:test:debug": "asc assembly/test.ts -o build/test.wasm --transform ./transform --config ./node_modules/@assemblyscript/wasi-shim/asconfig.json --optimizeLevel 0 --shrinkLevel 0 --noAssert --uncheckedBehavior always --runtime stub",
20
+ "build:bench": "asc bench/benchmark.ts -o bench/benchmark.wasm --transform ./transform --config ./node_modules/@assemblyscript/wasi-shim/asconfig.json --optimizeLevel 3 --shrinkLevel 0 --converge --noAssert --uncheckedBehavior always --runtime stub",
21
+ "bench:wasmtime": "wasmtime ./bench/benchmark.wasm",
22
+ "bench:wavm": "wavm run ./bench/benchmark.wasm",
19
23
  "build:transform": "tsc -p ./transform",
20
24
  "test:wasmtime": "wasmtime ./build/test.wasm",
25
+ "test:wavm": "wavm run ./build/test.wasm",
21
26
  "test:lunatic": "lunatic ./build/test.wasm",
22
27
  "test:wasm3": "wasm3 ./build/test.wasm",
23
28
  "prettier": "as-prettier -w ."
24
29
  },
25
30
  "devDependencies": {
26
31
  "@as-pect/cli": "^8.0.1",
27
- "@as-tral/cli": "^2.0.0",
32
+ "@as-tral/cli": "^2.0.1",
28
33
  "@assemblyscript/wasi-shim": "^0.1.0",
29
- "assemblyscript": "^0.27.8",
30
- "assemblyscript-prettier": "^1.0.7",
34
+ "assemblyscript": "^0.27.9",
35
+ "assemblyscript-prettier": "^2.0.2",
31
36
  "benchmark": "^2.1.4",
32
37
  "kati": "^0.6.2",
33
38
  "microtime": "^3.1.1",
34
- "prettier": "^2.8.4",
39
+ "prettier": "^3.0.2",
35
40
  "tinybench": "^2.5.0",
36
- "typescript": "^4.9.5",
41
+ "typescript": "^5.1.6",
37
42
  "visitor-as": "^0.11.4"
38
43
  },
39
44
  "dependencies": {
40
45
  "as-string-sink": "^0.5.3",
41
- "as-variant": "^0.4.1"
46
+ "as-variant": "^0.4.1",
47
+ "as-virtual": "^0.1.8"
42
48
  },
43
49
  "repository": {
44
50
  "type": "git",
@@ -90,22 +90,39 @@ class AsJSONTransform extends BaseVisitor {
90
90
  "i16",
91
91
  "u32",
92
92
  "i32",
93
- "f32",
94
93
  "u64",
95
94
  "i64",
95
+ ].includes(type.toLowerCase())) {
96
+ this.currentClass.encodeStmts.push(`"${name}":\${this.${name}.toString()},`);
97
+ // @ts-ignore
98
+ this.currentClass.setDataStmts.push(`if (key.equals("${name}")) {
99
+ this.${name} = __atoi_fast<${type}>(data, val_start << 1, val_end << 1);
100
+ return;
101
+ }
102
+ `);
103
+ }
104
+ else // @ts-ignore
105
+ if ([
106
+ "f32",
96
107
  "f64",
97
108
  ].includes(type.toLowerCase())) {
98
109
  this.currentClass.encodeStmts.push(`"${name}":\${this.${name}.toString()},`);
110
+ // @ts-ignore
111
+ this.currentClass.setDataStmts.push(`if (key.equals("${name}")) {
112
+ this.${name} = __parseObjectValue<${type}>(data.slice(val_start, val_end));
113
+ return;
114
+ }
115
+ `);
99
116
  }
100
117
  else {
101
118
  this.currentClass.encodeStmts.push(`"${name}":\${JSON.stringify<${type}>(this.${name})},`);
102
- }
103
- // @ts-ignore
104
- this.currentClass.setDataStmts.push(`if (key == "${name}") {
105
- this.${name} = JSON.parseObjectValue<${type}>(value);
119
+ // @ts-ignore
120
+ this.currentClass.setDataStmts.push(`if (key.equals("${name}")) {
121
+ this.${name} = __parseObjectValue<${type}>(val_start ? data.slice(val_start, val_end) : data);
106
122
  return;
107
123
  }
108
124
  `);
125
+ }
109
126
  }
110
127
  }
111
128
  let serializeFunc = "";
@@ -114,23 +131,20 @@ class AsJSONTransform extends BaseVisitor {
114
131
  this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] =
115
132
  stmt.slice(0, stmt.length - 1);
116
133
  serializeFunc = `
117
- @inline
118
- __JSON_Serialize(): string {
134
+ @inline __JSON_Serialize(): string {
119
135
  return \`{${this.currentClass.encodeStmts.join("")}}\`;
120
136
  }
121
137
  `;
122
138
  }
123
139
  else {
124
140
  serializeFunc = `
125
- @inline
126
- __JSON_Serialize(): string {
141
+ @inline __JSON_Serialize(): string {
127
142
  return "{}";
128
143
  }
129
144
  `;
130
145
  }
131
146
  const setKeyFunc = `
132
- @inline
133
- __JSON_Set_Key(key: string, value: string): void {
147
+ @inline __JSON_Set_Key<T>(key: T, data: string, val_start: i32, val_end: i32): void {
134
148
  ${
135
149
  // @ts-ignore
136
150
  this.currentClass.setDataStmts.join("")}
@@ -141,6 +155,7 @@ class AsJSONTransform extends BaseVisitor {
141
155
  const setDataMethod = SimpleParser.parseClassMember(setKeyFunc, node);
142
156
  node.members.push(setDataMethod);
143
157
  this.schemasList.push(this.currentClass);
158
+ //console.log(toString(node));
144
159
  }
145
160
  visitSource(node) {
146
161
  super.visitSource(node);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@json-as/transform",
3
- "version": "0.5.52",
3
+ "version": "0.5.54",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "main": "./lib/index.js",
6
6
  "author": "Jairus Tanaka",
@@ -23,7 +23,7 @@ class AsJSONTransform extends BaseVisitor {
23
23
  public currentClass!: SchemaData;
24
24
  public sources: Source[] = [];
25
25
 
26
- visitMethodDeclaration(): void {}
26
+ visitMethodDeclaration(): void { }
27
27
  visitClassDeclaration(node: ClassDeclaration): void {
28
28
  const className = node.name.text;
29
29
  if (!node.decorators?.length) return;
@@ -65,8 +65,8 @@ class AsJSONTransform extends BaseVisitor {
65
65
  } else {
66
66
  console.error(
67
67
  "Class extends " +
68
- this.currentClass.parent +
69
- ", but parent class not found. Maybe add the @json decorator over parent class?"
68
+ this.currentClass.parent +
69
+ ", but parent class not found. Maybe add the @json decorator over parent class?"
70
70
  );
71
71
  }
72
72
  }
@@ -103,28 +103,52 @@ class AsJSONTransform extends BaseVisitor {
103
103
  "i16",
104
104
  "u32",
105
105
  "i32",
106
- "f32",
107
106
  "u64",
108
107
  "i64",
109
- "f64",
110
108
  ].includes(type.toLowerCase())
111
109
  ) {
112
110
  this.currentClass.encodeStmts.push(
113
111
  `"${name}":\${this.${name}.toString()},`
114
112
  );
115
- } else {
113
+ // @ts-ignore
114
+ this.currentClass.setDataStmts.push(
115
+ `if (key.equals("${name}")) {
116
+ this.${name} = __atoi_fast<${type}>(data, val_start << 1, val_end << 1);
117
+ return;
118
+ }
119
+ `
120
+ );
121
+ } else // @ts-ignore
122
+ if (
123
+ [
124
+ "f32",
125
+ "f64",
126
+ ].includes(type.toLowerCase())
127
+ ) {
128
+ this.currentClass.encodeStmts.push(
129
+ `"${name}":\${this.${name}.toString()},`
130
+ );
131
+ // @ts-ignore
132
+ this.currentClass.setDataStmts.push(
133
+ `if (key.equals("${name}")) {
134
+ this.${name} = __parseObjectValue<${type}>(data.slice(val_start, val_end));
135
+ return;
136
+ }
137
+ `
138
+ );
139
+ } else {
116
140
  this.currentClass.encodeStmts.push(
117
141
  `"${name}":\${JSON.stringify<${type}>(this.${name})},`
118
142
  );
119
- }
120
- // @ts-ignore
121
- this.currentClass.setDataStmts.push(
122
- `if (key == "${name}") {
123
- this.${name} = JSON.parseObjectValue<${type}>(value);
143
+ // @ts-ignore
144
+ this.currentClass.setDataStmts.push(
145
+ `if (key.equals("${name}")) {
146
+ this.${name} = __parseObjectValue<${type}>(val_start ? data.slice(val_start, val_end) : data);
124
147
  return;
125
148
  }
126
149
  `
127
- );
150
+ );
151
+ }
128
152
  }
129
153
  }
130
154
 
@@ -133,32 +157,29 @@ class AsJSONTransform extends BaseVisitor {
133
157
  if (this.currentClass.encodeStmts.length > 0) {
134
158
  const stmt =
135
159
  this.currentClass.encodeStmts[
136
- this.currentClass.encodeStmts.length - 1
160
+ this.currentClass.encodeStmts.length - 1
137
161
  ]!;
138
162
  this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] =
139
163
  stmt!.slice(0, stmt.length - 1);
140
164
  serializeFunc = `
141
- @inline
142
- __JSON_Serialize(): string {
165
+ @inline __JSON_Serialize(): string {
143
166
  return \`{${this.currentClass.encodeStmts.join("")}}\`;
144
167
  }
145
168
  `;
146
169
  } else {
147
170
  serializeFunc = `
148
- @inline
149
- __JSON_Serialize(): string {
171
+ @inline __JSON_Serialize(): string {
150
172
  return "{}";
151
173
  }
152
174
  `;
153
175
  }
154
176
 
155
177
  const setKeyFunc = `
156
- @inline
157
- __JSON_Set_Key(key: string, value: string): void {
178
+ @inline __JSON_Set_Key<T>(key: T, data: string, val_start: i32, val_end: i32): void {
158
179
  ${
159
- // @ts-ignore
160
- this.currentClass.setDataStmts.join("")
161
- }
180
+ // @ts-ignore
181
+ this.currentClass.setDataStmts.join("")
182
+ }
162
183
  }
163
184
  `;
164
185
 
@@ -169,6 +190,7 @@ class AsJSONTransform extends BaseVisitor {
169
190
  node.members.push(setDataMethod);
170
191
 
171
192
  this.schemasList.push(this.currentClass);
193
+ //console.log(toString(node));
172
194
  }
173
195
  visitSource(node: Source): void {
174
196
  super.visitSource(node);