json-as 0.8.4 → 0.8.6

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.
package/CHANGELOG CHANGED
@@ -1,3 +1,5 @@
1
1
  v0.8.2 - Properties starting with `static` or `private` would be ignored
2
2
  v0.8.3 - Dirty fix to issue #68. Add __JSON_Stringify callable to global scope.
3
- v0.8.4 - Fix #71. Classes with the extending class overriding a property cause the property to be serialized twice.
3
+ v0.8.4 - Fix #71. Classes with the extending class overriding a property cause the property to be serialized twice.
4
+ v0.8.5 - Fix #73. Support for nullable primatives with Box<T> from as-container
5
+ v0.8.6 - Fix. Forgot to stash before publishing. Stash and push what should have been v0.8.5
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  ██║ ██║███████║ ╚█████╔╝███████║╚██████╔╝██║ ╚████║
8
8
  ╚═╝ ╚═╝╚══════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═══╝
9
9
 
10
- v0.8.3
10
+ v0.8.6
11
11
  </pre>
12
12
  </h3>
13
13
 
@@ -80,6 +80,43 @@ const parsed = JSON.parse<Player>(stringified);
80
80
 
81
81
  If you use this project in your codebase, consider dropping a [star](https://github.com/JairusSW/as-json). I would really appreciate it!
82
82
 
83
+ ## Performance
84
+
85
+ Run or view the benchmarks [here](https://github.com/JairusSW/as-json/tree/master/bench)
86
+
87
+ Below are benchmark results comparing JavaScript's built-in JSON implementation and `JSON-AS`
88
+
89
+ My library beats JSON (written in C++) on all counts *and*, I see many places where I can pull at least a 60% uplift in performance if I implement it.
90
+
91
+
92
+ Serialization Benchmarks:
93
+
94
+ | Value | JavaScript (ops/s) | JSON-as (ops/s) | JSON-AS with Pages |
95
+ |----------------------------|--------------------|-----------------|--------------------|
96
+ | "hello world" | 28,629,598 | 64,210,666 | + 124% |
97
+ | 12345 | 31,562,431 | 56,329,066 | 321,783,941 ops/s |
98
+ | 1.2345 | 15,977,278 | 20,322,939 | 30,307,616 ops/s |
99
+ | [[],[[]],[[],[[]]]] | 8,998,624 | 34,453,102 | + 283% |
100
+
101
+
102
+
103
+ Deserialization Benchmarks: (WIP)
104
+
105
+ | Value | JavaScript (ops/s) | JSON-AS (ops/s) | % Diff |
106
+ |----------------------------|--------------------|-----------------|--------|
107
+ | "12345" | 34,647,886 | 254,640,930 | + 635% |
108
+
109
+
110
+ And my PC specs:
111
+
112
+ | Component | Specification |
113
+ |-----------------|--------------------------------------|
114
+ | Wasmer Version | v4.3.0 |
115
+ | CPU | AMD Ryzen 7 7800x3D @ 6.00 GHz |
116
+ | Memory | T-Force DDR5 6000 MHz |
117
+ | OS | Ubuntu WSL2 |
118
+ | Graphics | AMD Radeon RX 6750XT |
119
+
83
120
  ## Issues
84
121
 
85
122
  Please submit an issue to https://github.com/JairusSW/as-json/issues if you find anything wrong with this library
@@ -53,6 +53,8 @@ class Vec3 {
53
53
  x: f64;
54
54
  y: f64;
55
55
  z: f64;
56
+
57
+ static shouldIgnore: string = "should not be serialized";
56
58
  }
57
59
 
58
60
  @json
@@ -12,3 +12,13 @@ declare function serializable(target: any): void;
12
12
  * Property decorator that provides an alias name for JSON serialization.
13
13
  */
14
14
  declare function alias(name: string): Function;
15
+
16
+ /**
17
+ * Property decorator that allows a field to be omitted when equal to an Expression.
18
+ */
19
+ declare function omitwhen(condition: string): Function;
20
+
21
+ /**
22
+ * Property decorator that allows a field to be omitted when a property is null.
23
+ */
24
+ declare function omitnull(): Function;
@@ -42,6 +42,7 @@ import {
42
42
  } from "./chars";
43
43
  import { snip_fast, unsafeCharCodeAt, containsCodePoint } from "./util";
44
44
  import { Virtual } from "as-virtual/assembly";
45
+ import { Box } from "as-container/assembly";
45
46
 
46
47
  /**
47
48
  * JSON Encoder/Decoder for AssemblyScript
@@ -62,7 +63,12 @@ export namespace JSON {
62
63
  return serializeString(data as string);
63
64
  } else if (isBoolean<T>()) {
64
65
  return data ? "true" : "false";
65
- } else if (isNullable<T>() && data == null) {
66
+ } else if (data instanceof Box) {
67
+ if (isNullable<T>() && (changetype<usize>(data._val) == <usize>0 || changetype<usize>(data) == <usize>0)) {
68
+ return nullWord;
69
+ }
70
+ return JSON.stringify(data.unwrap());
71
+ } else if (isNullable<T>() && changetype<usize>(data) == <usize>0) {
66
72
  return nullWord;
67
73
  // @ts-ignore
68
74
  } else if ((isInteger<T>() || isFloat<T>()) && isFinite(data)) {
@@ -130,91 +136,15 @@ export namespace JSON {
130
136
  result.writeCodePoint(rightBraceCode);
131
137
  return result.toString();
132
138
  } else {
133
- throw abort(
139
+ throw new Error(
134
140
  `Could not serialize data of type ${nameof<T>()}. Make sure to add the correct decorators to classes.`
135
141
  );
136
142
  }
137
143
  }
138
- /**
139
- * Stringifies valid JSON data.
140
- * ```js
141
- * __JSON_Stringify<T>(data)
142
- * ```
143
- * @param data T
144
- * @returns string
145
- */
146
144
  // @ts-ignore: Decorator
145
+ @unsafe
147
146
  @inline export function stringifyTo<T>(data: T, out: string): void {
148
- // String
149
- if (isString<T>() && data != null) {
150
- out = serializeString(data as string);
151
- return;
152
- } else if (isBoolean<T>()) {
153
- out = data ? trueWord : falseWord;
154
- return;
155
- } else if (isNullable<T>() && data == null) {
156
- out = nullWord;
157
- return;
158
- // @ts-ignore
159
- } else if ((isInteger<T>() || isFloat<T>()) && isFinite(data)) {
160
- // @ts-ignore
161
- out = data.toString();
162
- return;
163
- // @ts-ignore: Hidden function
164
- } else if (isDefined(data.__JSON_Serialize)) {
165
- // @ts-ignore: Hidden function
166
- out = data.__JSON_Serialize();
167
- return;
168
- } else if (data instanceof Date) {
169
- out = quoteWord + data.toISOString() + quoteWord;
170
- return;
171
- } else if (isArrayLike<T>()) {
172
- // @ts-ignore
173
- if (data.length == 0) {
174
- out = emptyArrayWord;
175
- return;
176
- // @ts-ignore
177
- } else if (isString<valueof<T>>()) {
178
- out = leftBracketWord;
179
- // @ts-ignore
180
- for (let i = 0; i < data.length - 1; i++) {
181
- // @ts-ignore
182
- out += serializeString(unchecked(data[i]));
183
- out += commaWord;
184
- }
185
- // @ts-ignore
186
- out += serializeString(unchecked(data[data.length - 1]));
187
- out += rightBracketWord;
188
- return;
189
- // @ts-ignore
190
- } else if (isBoolean<valueof<T>>()) {
191
- // @ts-ignore
192
- out = leftBracketWord + data.join(commaWord) + rightBracketWord;
193
- return;
194
- // @ts-ignore
195
- } else if (isFloat<valueof<T>>() || isInteger<valueof<T>>()) {
196
- // @ts-ignore
197
- out = leftBracketWord + data.join(commaWord) + rightBracketWord;
198
- return;
199
- } else {
200
- let result = new StringSink(leftBracketWord);
201
- // @ts-ignore
202
- for (let i = 0; i < data.length - 1; i++) {
203
- // @ts-ignore
204
- result.write(__JSON_Stringify(unchecked(data[i])));
205
- result.writeCodePoint(commaCode);
206
- }
207
- // @ts-ignore
208
- result.write(__JSON_Stringify(unchecked(data[data.length - 1])));
209
- result.writeCodePoint(rightBracketCode);
210
- out = result.toString();
211
- return;
212
- }
213
- } else {
214
- throw abort(
215
- `Could not serialize data of type ${nameof<T>()}. Make sure to add the correct decorators to classes.`
216
- );
217
- }
147
+ throw new Error("Method is deprecated");
218
148
  }
219
149
  /**
220
150
  * Parses valid JSON strings into their original format.
@@ -227,7 +157,6 @@ export namespace JSON {
227
157
 
228
158
  // @ts-ignore: Decorator
229
159
  @inline export function parse<T>(data: string, initializeDefaultValues: boolean = false): T {
230
- let type: T;
231
160
  if (isString<T>()) {
232
161
  // @ts-ignore
233
162
  return parseString(data);
@@ -239,6 +168,15 @@ export namespace JSON {
239
168
  } else if (isArrayLike<T>()) {
240
169
  // @ts-ignore
241
170
  return parseArray<T>(data.trimStart());
171
+ // @ts-ignore
172
+ }
173
+ let type: nonnull<T> = changetype<nonnull<T>>(0);
174
+ if (type instanceof Box) {
175
+ const instance = changetype<nonnull<T>>(__new(offsetof<nonnull<T>>(), idof<nonnull<T>>()))// as Box<usize>;
176
+ const val = instance._val;
177
+ instance._val = parseDirectInference(val, data);
178
+ // @ts-ignore
179
+ return changetype<T>(instance);
242
180
  } else if (isNullable<T>() && data == nullWord) {
243
181
  // @ts-ignore
244
182
  return null;
@@ -251,7 +189,7 @@ export namespace JSON {
251
189
  // @ts-ignore
252
190
  return parseDate(data);
253
191
  } else {
254
- throw abort(
192
+ throw new Error(
255
193
  `Could not deserialize data ${data} to type ${nameof<T>()}. Make sure to add the correct decorators to classes.`
256
194
  );
257
195
  }
@@ -260,7 +198,6 @@ export namespace JSON {
260
198
 
261
199
  // @ts-ignore: Decorator
262
200
  @global @inline function __parseObjectValue<T>(data: string, initializeDefaultValues: boolean): T {
263
- let type: T;
264
201
  if (isString<T>()) {
265
202
  // @ts-ignore
266
203
  return data;
@@ -272,6 +209,15 @@ export namespace JSON {
272
209
  } else if (isArrayLike<T>()) {
273
210
  // @ts-ignore
274
211
  return parseArray<T>(data);
212
+ // @ts-ignore
213
+ }
214
+ let type: nonnull<T> = changetype<nonnull<T>>(0);
215
+ if (type instanceof Box) {
216
+ const instance = changetype<nonnull<T>>(__new(offsetof<nonnull<T>>(), idof<nonnull<T>>()))// as Box<usize>;
217
+ const val = instance._val;
218
+ instance._val = parseDirectInference(val, data);
219
+ // @ts-ignore
220
+ return changetype<T>(instance);
275
221
  } else if (isNullable<T>() && data == nullWord) {
276
222
  // @ts-ignore
277
223
  return null;
@@ -284,7 +230,7 @@ export namespace JSON {
284
230
  // @ts-ignore
285
231
  return parseDate(data);
286
232
  } else {
287
- throw abort(
233
+ throw new Error(
288
234
  `Could not deserialize data ${data} to type ${nameof<T>()}. Make sure to add the correct decorators to classes.`
289
235
  );
290
236
  }
@@ -411,7 +357,7 @@ export namespace JSON {
411
357
  break;
412
358
  }
413
359
  default: {
414
- throw abort(`JSON: Cannot parse "${data}" as string. Invalid escape sequence: \\${data.charAt(i)}`);
360
+ throw new Error(`JSON: Cannot parse "${data}" as string. Invalid escape sequence: \\${data.charAt(i)}`);
415
361
  }
416
362
  }
417
363
  }
@@ -425,7 +371,7 @@ export namespace JSON {
425
371
  @inline function parseBoolean<T extends boolean>(data: string): T {
426
372
  if (data.length > 3 && data.startsWith(trueWord)) return <T>true;
427
373
  else if (data.length > 4 && data.startsWith(falseWord)) return <T>false;
428
- else throw abort(`JSON: Cannot parse "${data}" as boolean`);
374
+ else throw new Error(`JSON: Cannot parse "${data}" as boolean`);
429
375
  }
430
376
 
431
377
  // @ts-ignore: Decorator
@@ -442,6 +388,18 @@ export namespace JSON {
442
388
  else if (type instanceof f32) return f32.parse(data);
443
389
  }
444
390
 
391
+ // @ts-ignore: Decorator
392
+ @inline function parseNumberDirectInference<T>(type: T, data: string): T {
393
+ if (isInteger(type)) {
394
+ // @ts-ignore
395
+ return snip_fast<T>(data);
396
+ }
397
+ // @ts-ignore
398
+ if (type instanceof f64) return f64.parse(data);
399
+ // @ts-ignore
400
+ else if (type instanceof f32) return f32.parse(data);
401
+ }
402
+
445
403
  // @ts-ignore: Decorator
446
404
  @inline function parseObject<T>(data: string, initializeDefaultValues: boolean): T {
447
405
  const schema: nonnull<T> = changetype<nonnull<T>>(
@@ -584,7 +542,7 @@ export namespace JSON {
584
542
  );
585
543
 
586
544
  if (!isDefined(map.set)) {
587
- throw abort("Tried to parse a map, but the types did not match!")
545
+ throw new Error("Tried to parse a map, but the types did not match!")
588
546
  }
589
547
 
590
548
  const key = Virtual.createEmpty<string>();
@@ -729,7 +687,7 @@ export namespace JSON {
729
687
  return parseNumber<T>(k);
730
688
  }
731
689
 
732
- throw abort(`JSON: Cannot parse JSON object to a Map with a key of type ${nameof<T>()}`);
690
+ throw new Error(`JSON: Cannot parse JSON object to a Map with a key of type ${nameof<T>()}`);
733
691
  }
734
692
 
735
693
  // @ts-ignore: Decorator
@@ -758,7 +716,7 @@ export namespace JSON {
758
716
  }
759
717
  }
760
718
 
761
- throw abort("Tried to parse array, but failed!")
719
+ throw new Error("Tried to parse array, but failed!")
762
720
  }
763
721
 
764
722
  // @ts-ignore: Decorator
@@ -899,7 +857,7 @@ function parseDate(dateTimeString: string): Date {
899
857
  return serializeString(data as string);
900
858
  } else if (isBoolean<T>()) {
901
859
  return data ? "true" : "false";
902
- } else if (isNullable<T>() && data == null) {
860
+ } else if (isNullable<T>() && changetype<usize>(data) == <usize>0) {
903
861
  return nullWord;
904
862
  // @ts-ignore
905
863
  } else if ((isInteger<T>() || isFloat<T>()) && isFinite(data)) {
@@ -911,6 +869,11 @@ function parseDate(dateTimeString: string): Date {
911
869
  return data.__JSON_Serialize();
912
870
  } else if (data instanceof Date) {
913
871
  return `"${data.toISOString()}"`;
872
+ } else if (data instanceof Box) {
873
+ if (isNullable<T>() && changetype<usize>(data) == <usize>0) {
874
+ return nullWord;
875
+ }
876
+ return JSON.stringify(data.unwrap());
914
877
  } else if (isArrayLike<T>()) {
915
878
  // @ts-ignore
916
879
  if (data.length == 0) {
@@ -967,8 +930,12 @@ function parseDate(dateTimeString: string): Date {
967
930
  result.writeCodePoint(rightBraceCode);
968
931
  return result.toString();
969
932
  } else {
970
- throw abort(
933
+ throw new Error(
971
934
  `Could not serialize data of type ${nameof<T>()}. Make sure to add the correct decorators to classes.`
972
935
  );
973
936
  }
937
+ }
938
+
939
+ @inline function parseDirectInference<T>(type: T, data: string, initializeDefaultValues: boolean = false): T {
940
+ return JSON.parse<T>(data, initializeDefaultValues)
974
941
  }
package/assembly/test.ts CHANGED
@@ -1,24 +1,23 @@
1
+ import { Box } from "as-container";
1
2
  import { JSON } from "./src/json";
2
3
 
3
4
  @json
4
- class BaseObject {
5
- a: string;
6
-
7
- constructor(a: string) {
8
- this.a = a;
9
- }
5
+ class Foo {
6
+ @omitnull
7
+ optionalNumber: Box<i32> | null = null;
8
+ @omitif("this.tristateValue!.unwrap() == false")
9
+ tristateValue: Box<bool> | null = null;
10
10
  }
11
11
 
12
- @json
13
- class DerivedObject extends BaseObject {
14
- b: string;
15
-
16
- constructor(a: string, b: string) {
17
- super(a);
18
- this.b = b;
19
- }
12
+ const foo: Foo = {
13
+ optionalNumber: null,
14
+ tristateValue: Box.from(true)
20
15
  }
21
16
 
22
- const o = new DerivedObject("1", "2");
17
+ console.log(JSON.stringify(foo));
23
18
 
24
- console.log(JSON.stringify(o))
19
+ const p1 = JSON.parse<Box<i32> | null>("null");
20
+ console.log(JSON.stringify<Box<i32> | null>(p1));
21
+ console.log(changetype<usize>(p1).toString())
22
+ const p2 = JSON.parse<Foo>("{\"optionalNumber\":null,\"tristateValue\":false}");
23
+ console.log(JSON.stringify(p2));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-as",
3
- "version": "0.8.4",
3
+ "version": "0.8.6",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "types": "assembly/index.ts",
6
6
  "author": "Jairus Tanaka",
@@ -44,9 +44,10 @@
44
44
  "visitor-as": "^0.11.4"
45
45
  },
46
46
  "dependencies": {
47
+ "as-container": "^0.8.0",
47
48
  "as-string-sink": "^0.5.3",
48
49
  "as-variant": "^0.4.1",
49
- "as-virtual": "^0.1.9"
50
+ "as-virtual": "^0.2.0"
50
51
  },
51
52
  "overrides": {
52
53
  "assemblyscript": "$assemblyscript"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@json-as/transform",
3
- "version": "0.8.4",
3
+ "version": "0.8.6",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "main": "./lib/index.js",
6
6
  "author": "Jairus Tanaka",
@@ -25,6 +25,8 @@
25
25
  "json",
26
26
  "serialize",
27
27
  "deserialize",
28
+ "stringify",
29
+ "data",
28
30
  "serde"
29
31
  ],
30
32
  "bugs": {
@@ -309,4 +309,4 @@ export default class Transformer extends Transform {
309
309
  }
310
310
  }
311
311
  }
312
- }
312
+ }