json-as 0.5.38 → 0.5.41

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.
@@ -114,6 +114,10 @@ export function parseSciInteger<T extends number>(str: string): T {
114
114
  // @ts-ignore
115
115
  let val: T = 0;
116
116
  let offset = 0;
117
+ let firstChar = load<u16>(changetype<usize>(str) + <usize>offset);
118
+ if (firstChar === 45) {
119
+ offset = 2;
120
+ }
117
121
  for (; offset < str.length << 1; offset += 2) {
118
122
  const char = load<u16>(changetype<usize>(str) + <usize>offset);
119
123
  if (char === 101 || char === 69) {
@@ -134,6 +138,9 @@ export function parseSciInteger<T extends number>(str: string): T {
134
138
  val = (val << 1) + (val << 3) + (char - 48);
135
139
  // We use load because in this case, there is no need to have bounds-checking
136
140
  }
141
+ if (firstChar === 45) {
142
+ val = -val;
143
+ }
137
144
  return val;
138
145
  }
139
146
 
@@ -141,15 +148,16 @@ export function parseSciInteger<T extends number>(str: string): T {
141
148
  @inline
142
149
  function sciNote<T extends number>(num: T): T {
143
150
  let res = 1;
144
- if (num > 0) {
145
- for (let i = 0; i < num; i++) {
146
- res *= 10;
147
- }
148
- } else {
149
- for (let i = 0; i < num; i++) {
150
- res /= 10;
151
+ // @ts-ignore
152
+ if (num > 0) {
153
+ for (let i: T = 0; i < num; i++) {
154
+ res *= 10;
155
+ }
156
+ } else {
157
+ for (let i: T = 0; i < num; i++) {
158
+ res /= 10;
159
+ }
151
160
  }
152
- }
153
161
  // @ts-ignore
154
162
  return res;
155
- }
163
+ }
package/assembly/test.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { JSON } from "./src/json";
2
2
  import { atoi_fast, parseSciInteger } from "./src/util";
3
- import * as a from "util/number"
3
+ import * as a from "util/number";
4
4
  @json
5
5
  class Vec3 {
6
6
  x!: f32;
@@ -54,7 +54,30 @@ console.log("1230 - " + parseSciInteger<i32>("123e1").toString());
54
54
  console.log("12300 - " + parseSciInteger<i32>("123e2").toString());
55
55
  console.log("123000 - " + parseSciInteger<i32>("123e3").toString());
56
56
  console.log("32 - " + parseSciInteger<i32>("123e-1").toString());
57
+ console.log(parseSciInteger<i32>("100").toString());
58
+ console.log(parseSciInteger<i32>("-100").toString());
57
59
 
60
+ console.log(
61
+ JSON.stringify([
62
+ "abcdefg",
63
+ 'st"ring" w""ith quotes"',
64
+ 'string \t\r"with ran\tdom spa\nces and \nnewlines\n\n\n',
65
+ 'string with colon : comma , brace [ ] bracket { } and quote " and other quote "',
66
+ ])
67
+ );/*
68
+ console.log(
69
+ JSON.stringify(
70
+ JSON.parse<string[]>(
71
+ JSON.stringify([
72
+ "abcdefg",
73
+ 'st"ring" w""ith quotes"',
74
+ 'string \t\r"with ran\tdom spa\nces and \nnewlines\n\n\n',
75
+ 'string with colon : comma , brace [ ] bracket { } and quote " and other quote "',
76
+ ])
77
+ )
78
+ )
79
+ );
80
+ /*
58
81
  const str = changetype<string>(new ArrayBuffer(6));
59
82
  console.log("istr:");
60
83
  console.log("123 - " + istr8(123));
@@ -63,7 +86,9 @@ console.log("3 - " + istr8(3));
63
86
 
64
87
  console.log(Uint8Array.wrap(changetype<ArrayBuffer>(istr8(12))).join(" "));
65
88
  console.log(load<u32>(changetype<usize>(istr8(12))).toString());
66
- @inline function istr8<T extends number>(int: T): string {
89
+ @inline function istr8<
90
+ T extends number
91
+ >(int: T): string {
67
92
  if (int >= 100) {
68
93
  const str = changetype<string>(__new(6, idof<String>()));
69
94
  store<u16>(changetype<usize>(str), ((int / 100) % 10) + 48);
@@ -222,9 +247,11 @@ export function istr32<T extends number>(int: T): string {
222
247
  export function istr64<T extends number>(int: T): string {
223
248
  const val = new ArrayBuffer(6);
224
249
  store<u16>(changetype<usize>(val), (int % 10) + 48, 4);
225
- if ((int = int / 10 as T) > 0) store<u16>(changetype<usize>(val), (int % 10) + 48, 2);
250
+ if ((int = (int / 10) as T) > 0)
251
+ store<u16>(changetype<usize>(val), (int % 10) + 48, 2);
226
252
  else return changetype<string>(val);
227
- if ((int = int / 10 as T) > 0) store<u16>(changetype<usize>(val), (int % 10) + 48);
253
+ if ((int = (int / 10) as T) > 0)
254
+ store<u16>(changetype<usize>(val), (int % 10) + 48);
228
255
  return changetype<string>(val);
229
256
  }
230
257
 
@@ -239,4 +266,5 @@ export function istr64<T extends number>(int: T): string {
239
266
  // 8 = 56
240
267
  // 9 = 57
241
268
 
242
- console.log(JSON.stringify("h\\i from gray\bson"))
269
+ console.log(JSON.stringify("h\\i from gray\bson"));
270
+ */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-as",
3
- "version": "0.5.38",
3
+ "version": "0.5.41",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "types": "assembly/index.ts",
6
6
  "author": "Jairus Tanaka",
@@ -1,4 +1,4 @@
1
- import { toString, isStdlib } from "visitor-as/dist/utils.js";
1
+ import { getName, toString, isStdlib } from "visitor-as/dist/utils.js";
2
2
  import { BaseVisitor, SimpleParser } from "visitor-as/dist/index.js";
3
3
  import { Transform } from "assemblyscript/dist/transform.js";
4
4
  class SchemaData {
@@ -19,10 +19,38 @@ class AsJSONTransform extends BaseVisitor {
19
19
  this.sources = [];
20
20
  }
21
21
  visitMethodDeclaration() { }
22
+ visitFieldDeclaration(node) {
23
+ if (toString(node).startsWith("static"))
24
+ return;
25
+ const lineText = toString(node);
26
+ if (lineText.startsWith("private"))
27
+ return;
28
+ const name = getName(node);
29
+ if (!node.type) {
30
+ throw new Error(`Field ${name} is missing a type declaration`);
31
+ }
32
+ let type = getName(node.type);
33
+ // @ts-ignore
34
+ this.currentClass.encodeStmts.push(`"${name}":\${JSON.stringify<${type}>(this.${name})},`);
35
+ // @ts-ignore
36
+ //this.decodeStmts.push(
37
+ // `${name}: JSON.parseObjectValue<${type}>(values.get("${name}")),\n`
38
+ //);
39
+ // @ts-ignore
40
+ this.currentClass.setDataStmts.push(`if (key.length === ${name.length} && (memory.compare(changetype<usize>("${name}"), changetype<usize>(key), ${name.length}) == 0)) {
41
+ this.${name} = JSON.parseObjectValue<${type}>(value);
42
+ return;
43
+ }
44
+ `);
45
+ // @ts-ignore
46
+ //this.checkDecodeStmts.push(
47
+ // ' if (!values.has("${name}")) throw new Error("Key "${name}" was not found. Cannot instantiate object.");\n'
48
+ //);
49
+ }
22
50
  visitClassDeclaration(node) {
23
- var _c;
51
+ var _a;
24
52
  const className = node.name.text;
25
- if (!((_c = node.decorators) === null || _c === void 0 ? void 0 : _c.length))
53
+ if (!((_a = node.decorators) === null || _a === void 0 ? void 0 : _a.length))
26
54
  return;
27
55
  let foundDecorator = false;
28
56
  for (const decorator of node.decorators) {
@@ -32,7 +60,7 @@ class AsJSONTransform extends BaseVisitor {
32
60
  }
33
61
  if (!foundDecorator)
34
62
  return;
35
- // Prevent from being triggered twice.
63
+ // Prevent from being triggered twice
36
64
  for (const member of node.members) {
37
65
  if (member.name.text == "__JSON_Serialize")
38
66
  return;
@@ -45,7 +73,7 @@ class AsJSONTransform extends BaseVisitor {
45
73
  parent: node.extendsType ? toString(node.extendsType) : "",
46
74
  node: node,
47
75
  encodeStmts: [],
48
- setDataStmts: [],
76
+ setDataStmts: []
49
77
  };
50
78
  if (this.currentClass.parent.length > 0) {
51
79
  const parentSchema = this.schemasList.find((v) => v.name == this.currentClass.parent);
@@ -54,63 +82,17 @@ class AsJSONTransform extends BaseVisitor {
54
82
  this.currentClass.encodeStmts.push(...parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.encodeStmts);
55
83
  }
56
84
  else {
57
- console.error("Class extends " +
58
- this.currentClass.parent +
59
- ", but parent class not found. Maybe add the @json decorator over parent class?");
85
+ console.error("Class extends " + this.currentClass.parent + ", but parent class not found. Maybe add the @json decorator over parent class?");
60
86
  }
61
87
  }
62
88
  const parentSchema = this.schemasList.find((v) => v.name == this.currentClass.parent);
63
- const members = [
64
- ...node.members,
65
- ...(parentSchema ? parentSchema.node.members : []),
66
- ];
67
- for (const mem of members) {
68
- if (mem.type && mem.type.name && mem.type.name.identifier.text) {
69
- const member = mem;
70
- if (toString(member).startsWith("static"))
71
- return;
72
- const lineText = toString(member);
73
- if (lineText.startsWith("private"))
74
- return;
75
- // @ts-ignore
76
- let type = toString(member.type);
77
- const name = member.name.text;
78
- this.currentClass.keys.push(name);
79
- // @ts-ignore
80
- this.currentClass.types.push(type);
81
- // @ts-ignore
82
- if ([
83
- "u8",
84
- "i8",
85
- "u16",
86
- "i16",
87
- "u32",
88
- "i32",
89
- "f32",
90
- "u64",
91
- "i64",
92
- "f64",
93
- ].includes(type.toLowerCase())) {
94
- this.currentClass.encodeStmts.push(`"${name}":\${this.${name}.toString()},`);
95
- }
96
- else {
97
- this.currentClass.encodeStmts.push(`"${name}":\${JSON.stringify<${type}>(this.${name})},`);
98
- }
99
- // @ts-ignore
100
- this.currentClass.setDataStmts.push(`if (key == "${name}") {
101
- this.${name} = JSON.parseObjectValue<${type}>(value);
102
- return;
103
- }
104
- `);
105
- }
106
- }
89
+ const members = [...node.members, ...(parentSchema ? parentSchema.node.members : [])];
90
+ this.visit(members);
107
91
  let serializeFunc = "";
108
92
  if (this.currentClass.encodeStmts.length > 0) {
109
93
  const stmt = this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1];
110
- this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] =
111
- stmt.slice(0, stmt.length - 1);
94
+ this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] = stmt.slice(0, stmt.length - 1);
112
95
  serializeFunc = `
113
- @inline
114
96
  __JSON_Serialize(): string {
115
97
  return \`{${this.currentClass.encodeStmts.join("")}}\`;
116
98
  }
@@ -118,18 +100,16 @@ class AsJSONTransform extends BaseVisitor {
118
100
  }
119
101
  else {
120
102
  serializeFunc = `
121
- @inline
122
103
  __JSON_Serialize(): string {
123
104
  return "{}";
124
105
  }
125
106
  `;
126
107
  }
127
108
  const setKeyFunc = `
128
- @inline
129
109
  __JSON_Set_Key(key: string, value: string): void {
130
110
  ${
131
- // @ts-ignore
132
- this.currentClass.setDataStmts.join("")}
111
+ // @ts-ignore
112
+ this.currentClass.setDataStmts.join("")}
133
113
  }
134
114
  `;
135
115
  const serializeMethod = SimpleParser.parseClassMember(serializeFunc, node);
@@ -147,23 +127,18 @@ export default class Transformer extends Transform {
147
127
  afterParse(parser) {
148
128
  // Create new transform
149
129
  const transformer = new AsJSONTransform();
150
- // Sort the sources so that user scripts are visited last
151
- const sources = parser.sources
152
- .filter((source) => !isStdlib(source))
153
- .sort((_a, _b) => {
154
- const a = _a.internalPath;
155
- const b = _b.internalPath;
130
+ // Loop over every source
131
+ const sources = parser.sources.filter(source => !isStdlib(source)).sort((_a, _b) => {
132
+ const a = _a.internalPath
133
+ const b = _b.internalPath
156
134
  if (a[0] === "~" && b[0] !== "~") {
157
135
  return -1;
158
- }
159
- else if (a[0] !== "~" && b[0] === "~") {
136
+ } else if (a[0] !== "~" && b[0] === "~") {
160
137
  return 1;
161
- }
162
- else {
138
+ } else {
163
139
  return 0;
164
140
  }
165
- });
166
- // Loop over every source
141
+ })
167
142
  for (const source of sources) {
168
143
  // Ignore all lib and std. Visit everything else.
169
144
  if (!isStdlib(source)) {
@@ -171,4 +146,4 @@ export default class Transformer extends Transform {
171
146
  }
172
147
  }
173
148
  }
174
- }
149
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@json-as/transform",
3
- "version": "0.5.38",
3
+ "version": "0.5.41",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "main": "./lib/index.js",
6
6
  "author": "Jairus Tanaka",
@@ -23,14 +23,19 @@ 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;
30
30
  let foundDecorator = false;
31
31
  for (const decorator of node.decorators!) {
32
- // @ts-ignore
33
- if (decorator.name.text.toLowerCase() == "json" || decorator.name.text.toLowerCase() == "serializable") foundDecorator = true;
32
+ if (
33
+ // @ts-ignore
34
+ decorator.name.text.toLowerCase() == "json" ||
35
+ // @ts-ignore
36
+ decorator.name.text.toLowerCase() == "serializable"
37
+ )
38
+ foundDecorator = true;
34
39
  }
35
40
  if (!foundDecorator) return;
36
41
 
@@ -60,8 +65,8 @@ class AsJSONTransform extends BaseVisitor {
60
65
  } else {
61
66
  console.error(
62
67
  "Class extends " +
63
- this.currentClass.parent +
64
- ", 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?"
65
70
  );
66
71
  }
67
72
  }
@@ -75,8 +80,9 @@ class AsJSONTransform extends BaseVisitor {
75
80
  ];
76
81
 
77
82
  for (const mem of members) {
83
+ // @ts-ignore
78
84
  if (mem.type && mem.type.name && mem.type.name.identifier.text) {
79
- const member: FieldDeclaration = mem;
85
+ const member = mem as FieldDeclaration;
80
86
  if (toString(member).startsWith("static")) return;
81
87
  const lineText = toString(member);
82
88
  if (lineText.startsWith("private")) return;
@@ -127,7 +133,7 @@ class AsJSONTransform extends BaseVisitor {
127
133
  if (this.currentClass.encodeStmts.length > 0) {
128
134
  const stmt =
129
135
  this.currentClass.encodeStmts[
130
- this.currentClass.encodeStmts.length - 1
136
+ this.currentClass.encodeStmts.length - 1
131
137
  ]!;
132
138
  this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] =
133
139
  stmt!.slice(0, stmt.length - 1);
@@ -150,9 +156,9 @@ class AsJSONTransform extends BaseVisitor {
150
156
  @inline
151
157
  __JSON_Set_Key(key: string, value: string): void {
152
158
  ${
153
- // @ts-ignore
154
- this.currentClass.setDataStmts.join("")
155
- }
159
+ // @ts-ignore
160
+ this.currentClass.setDataStmts.join("")
161
+ }
156
162
  }
157
163
  `;
158
164
 
@@ -1,72 +0,0 @@
1
- // XXHash 32-bit as a starting point, see: https://cyan4973.github.io/xxHash
2
- // primes
3
- // @ts-ignore: decorator
4
- const XXH32_P1 = 2654435761;
5
- // @ts-ignore: decorator
6
- const XXH32_P2 = 2246822519;
7
- // @ts-ignore: decorator
8
- const XXH32_P3 = 3266489917;
9
- // @ts-ignore: decorator
10
- const XXH32_P4 = 668265263;
11
- // @ts-ignore: decorator
12
- const XXH32_P5 = 374761393;
13
- // @ts-ignore: decorator
14
- const XXH32_SEED = 0;
15
- function hash32(key, len = 4) {
16
- let h = XXH32_SEED + XXH32_P5 + len;
17
- h += key * XXH32_P3;
18
- h = rotl(h, 17) * XXH32_P4;
19
- h ^= h >> 15;
20
- h *= XXH32_P2;
21
- h ^= h >> 13;
22
- h *= XXH32_P3;
23
- h ^= h >> 16;
24
- return h;
25
- }
26
- function rotl(x, r) {
27
- return (x << r) | (x >>> (32 - r));
28
- }
29
- function mix(h, key) {
30
- return rotl(h + key * XXH32_P2, 13) * XXH32_P1;
31
- }
32
- export function hashStr(key) {
33
- if (key == null) return XXH32_SEED;
34
- let h = key.length;
35
- let len = h;
36
- let pos = 0;
37
- if (len >= 16) {
38
- let s1 = XXH32_SEED + XXH32_P1 + XXH32_P2;
39
- let s2 = XXH32_SEED + XXH32_P2;
40
- let s3 = XXH32_SEED;
41
- let s4 = XXH32_SEED - XXH32_P1;
42
- let end = len + pos - 16;
43
- while (pos <= end) {
44
- s1 = mix(s1, key.charCodeAt(pos));
45
- s2 = mix(s2, key.charCodeAt(pos + 1));
46
- s3 = mix(s3, key.charCodeAt(pos + 2));
47
- s4 = mix(s4, load(pos, 12));
48
- pos += 16;
49
- }
50
- h += rotl(s1, 1) + rotl(s2, 7) + rotl(s3, 12) + rotl(s4, 18);
51
- } else {
52
- h += XXH32_SEED + XXH32_P5;
53
- }
54
- let end = changetype(key) + len - 4;
55
- while (pos <= end) {
56
- h += load(pos) * XXH32_P3;
57
- h = rotl(h, 17) * XXH32_P4;
58
- pos += 4;
59
- }
60
- end = changetype(key) + len;
61
- while (pos < end) {
62
- h += load(pos) * XXH32_P5;
63
- h = rotl(h, 11) * XXH32_P1;
64
- pos++;
65
- }
66
- h ^= h >> 15;
67
- h *= XXH32_P2;
68
- h ^= h >> 13;
69
- h *= XXH32_P3;
70
- h ^= h >> 16;
71
- return h;
72
- }
@@ -1,15 +0,0 @@
1
- export var Types;
2
- (function (Types) {
3
- Types[(Types["String"] = 0)] = "String";
4
- Types[(Types["u8"] = 1)] = "u8";
5
- Types[(Types["i8"] = 2)] = "i8";
6
- Types[(Types["u16"] = 3)] = "u16";
7
- Types[(Types["i16"] = 4)] = "i16";
8
- Types[(Types["u32"] = 5)] = "u32";
9
- Types[(Types["i32"] = 6)] = "i32";
10
- Types[(Types["u64"] = 7)] = "u64";
11
- Types[(Types["i64"] = 8)] = "i64";
12
- Types[(Types["f32"] = 9)] = "f32";
13
- Types[(Types["f64"] = 10)] = "f64";
14
- Types[(Types["boolean"] = 11)] = "boolean";
15
- })(Types || (Types = {}));