json-as 1.0.0-beta.1 → 1.0.0-beta.11

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.
Files changed (72) hide show
  1. package/.trunk/configs/.markdownlint.yaml +2 -0
  2. package/.trunk/configs/.shellcheckrc +7 -0
  3. package/.trunk/configs/.yamllint.yaml +7 -0
  4. package/.trunk/trunk.yaml +37 -0
  5. package/CHANGELOG +65 -0
  6. package/README.md +275 -25
  7. package/assembly/__benches__/misc.bench.ts +0 -1
  8. package/assembly/__benches__/string.bench.ts +23 -0
  9. package/assembly/__benches__/struct.bench.ts +21 -0
  10. package/assembly/__tests__/arbitrary.spec.ts +1 -1
  11. package/assembly/__tests__/array.spec.ts +42 -1
  12. package/assembly/__tests__/bool.spec.ts +1 -1
  13. package/assembly/__tests__/box.spec.ts +1 -1
  14. package/assembly/__tests__/custom.spec.ts +42 -0
  15. package/assembly/__tests__/date.spec.ts +1 -1
  16. package/assembly/__tests__/float.spec.ts +4 -4
  17. package/assembly/__tests__/integer.spec.ts +1 -1
  18. package/assembly/__tests__/map.spec.ts +7 -0
  19. package/assembly/__tests__/null.spec.ts +1 -1
  20. package/assembly/__tests__/raw.spec.ts +23 -0
  21. package/assembly/__tests__/string.spec.ts +1 -1
  22. package/assembly/__tests__/{obj.spec.ts → struct.spec.ts} +18 -4
  23. package/assembly/__tests__/test.spec.ts +1 -1
  24. package/assembly/as-bs.d.ts +53 -0
  25. package/assembly/custom/bench.ts +26 -0
  26. package/assembly/deserialize/simple/arbitrary.ts +5 -4
  27. package/assembly/deserialize/simple/array/arbitrary.ts +1 -2
  28. package/assembly/deserialize/simple/array/array.ts +4 -3
  29. package/assembly/deserialize/simple/array/bool.ts +7 -7
  30. package/assembly/deserialize/simple/array/float.ts +2 -2
  31. package/assembly/deserialize/simple/array/integer.ts +1 -1
  32. package/assembly/deserialize/simple/array/map.ts +1 -1
  33. package/assembly/deserialize/simple/array/string.ts +3 -3
  34. package/assembly/deserialize/simple/array/struct.ts +14 -3
  35. package/assembly/deserialize/simple/array.ts +3 -0
  36. package/assembly/deserialize/simple/map.ts +93 -75
  37. package/assembly/deserialize/simple/object.ts +26 -16
  38. package/assembly/deserialize/simple/raw.ts +6 -0
  39. package/assembly/deserialize/simple/struct.ts +29 -16
  40. package/assembly/index.d.ts +15 -1
  41. package/assembly/index.ts +94 -13
  42. package/assembly/serialize/simd/string.ts +0 -1
  43. package/assembly/serialize/simple/array.ts +0 -1
  44. package/assembly/serialize/simple/bool.ts +0 -2
  45. package/assembly/serialize/simple/date.ts +0 -1
  46. package/assembly/serialize/simple/float.ts +0 -1
  47. package/assembly/serialize/simple/integer.ts +0 -1
  48. package/assembly/serialize/simple/map.ts +0 -1
  49. package/assembly/serialize/simple/object.ts +0 -1
  50. package/assembly/serialize/simple/raw.ts +14 -0
  51. package/assembly/serialize/simple/string.ts +0 -1
  52. package/assembly/test.ts +69 -28
  53. package/bench/bench.ts +15 -0
  54. package/bench/schemas.ts +5 -0
  55. package/bench/string.bench.ts +16 -0
  56. package/index.ts +1 -1
  57. package/lib/tsconfig.json +8 -0
  58. package/package.json +10 -6
  59. package/run-tests.sh +1 -1
  60. package/transform/lib/index.js +120 -46
  61. package/transform/lib/index.js.map +1 -1
  62. package/transform/src/index.ts +137 -54
  63. package/.gitmodules +0 -0
  64. package/as-test.config.json +0 -18
  65. package/modules/as-bs/LICENSE +0 -21
  66. package/modules/as-bs/README.md +0 -95
  67. package/modules/as-bs/assembly/state.ts +0 -8
  68. package/modules/as-bs/assembly/tsconfig.json +0 -97
  69. package/modules/as-bs/index.ts +0 -1
  70. package/modules/as-bs/package.json +0 -32
  71. /package/{modules/test/assembly → assembly/__tests__/lib}/index.ts +0 -0
  72. /package/{modules/as-bs/assembly/index.ts → lib/as-bs.ts} +0 -0
@@ -1,4 +1,4 @@
1
- import { ClassDeclaration, FieldDeclaration, IdentifierExpression, Parser, Source, NodeKind, Expression, CommonFlags, StringLiteralExpression, IntegerLiteralExpression, FloatLiteralExpression, NullExpression, TrueExpression, FalseExpression, CallExpression, ImportStatement, NamespaceDeclaration, Node, Statement, Tokenizer, SourceKind, PropertyAccessExpression, Token, CommentHandler, ExpressionStatement, BinaryExpression, NamedTypeNode, Range, FEATURE_SIMD, FunctionExpression } from "assemblyscript/dist/assemblyscript.js";
1
+ import { ClassDeclaration, FieldDeclaration, IdentifierExpression, Parser, Source, NodeKind, CommonFlags, ImportStatement, Node, Tokenizer, SourceKind, NamedTypeNode, Range, FEATURE_SIMD, FunctionExpression, MethodDeclaration } from "assemblyscript/dist/assemblyscript.js";
2
2
  import { Transform } from "assemblyscript/dist/transform.js";
3
3
  import { Visitor } from "./visitor.js";
4
4
  import { SimpleParser, toString } from "./util.js";
@@ -41,6 +41,79 @@ class JSONTransform extends Visitor {
41
41
  if (process.env["JSON_DEBUG"]) console.log("Created schema: " + this.schema.name);
42
42
 
43
43
  const members: FieldDeclaration[] = [...(node.members.filter((v) => v.kind === NodeKind.FieldDeclaration && v.flags !== CommonFlags.Static && v.flags !== CommonFlags.Private && v.flags !== CommonFlags.Protected && !v.decorators?.some((decorator) => (<IdentifierExpression>decorator.name).text === "omit")) as FieldDeclaration[])];
44
+ const serializers: MethodDeclaration[] = [...(node.members.filter((v) => v.kind === NodeKind.MethodDeclaration && v.decorators && v.decorators.some((e) => (<IdentifierExpression>e.name).text.toLowerCase() === "serializer")))] as MethodDeclaration[];
45
+ const deserializers: MethodDeclaration[] = [...(node.members.filter((v) => v.kind === NodeKind.MethodDeclaration && v.decorators && v.decorators.some((e) => (<IdentifierExpression>e.name).text.toLowerCase() === "deserializer")))] as MethodDeclaration[];
46
+
47
+ if (serializers.length > 1) throwError("Multiple serializers detected for class " + node.name.text + " but schemas can only have one serializer!", serializers[1].range);
48
+ if (deserializers.length > 1) throwError("Multiple deserializers detected for class " + node.name.text + " but schemas can only have one deserializer!", deserializers[1].range);
49
+
50
+ if (serializers.length) {
51
+ const serializer = serializers[0];
52
+ if (!serializer.signature.parameters.length) throwError("Could not find any parameters in custom serializer for " + this.schema.name + ". Serializers must have one parameter like 'serializer(self: " + this.schema.name + "): string {}'", serializer.range);
53
+ if (serializer.signature.parameters.length > 1) throwError("Found too many parameters in custom serializer for " + this.schema.name + ", but serializers can only accept one parameter of type '" + this.schema.name + "'!", serializer.signature.parameters[1].range);
54
+ if ((<NamedTypeNode>serializer.signature.parameters[0].type).name.identifier.text != node.name.text && (<NamedTypeNode>serializer.signature.parameters[0].type).name.identifier.text != "this") throwError("Type of parameter for custom serializer does not match! It should be 'string'either be 'this' or '" + this.schema.name + "'", serializer.signature.parameters[0].type.range);
55
+ if (!serializer.signature.returnType || !(<NamedTypeNode>serializer.signature.returnType).name.identifier.text.includes("string")) throwError("Could not find valid return type for serializer in " + this.schema.name + "!. Set the return type to type 'string' and try again", serializer.signature.returnType.range);
56
+
57
+ if (!serializer.decorators.some((v) => (<IdentifierExpression>v.name).text == "inline")) {
58
+ serializer.decorators.push(
59
+ Node.createDecorator(
60
+ Node.createIdentifierExpression(
61
+ "inline",
62
+ serializer.range
63
+ ),
64
+ null,
65
+ serializer.range
66
+ )
67
+ );
68
+ }
69
+ let SERIALIZER = "";
70
+ SERIALIZER += " @inline __SERIALIZE_CUSTOM(ptr: usize): void {\n";
71
+ SERIALIZER += " const data = this." + serializer.name.text + "(changetype<" + this.schema.name + ">(ptr));\n";
72
+ SERIALIZER += " if (isNullable(data) && changetype<usize>(data) == <usize>0) throw new Error(\"Could not serialize data using custom serializer!\");\n";
73
+ SERIALIZER += " const dataSize = data.length << 1;\n";
74
+ SERIALIZER += " memory.copy(bs.offset, changetype<usize>(data), dataSize);\n";
75
+ SERIALIZER += " bs.offset += dataSize;\n";
76
+ SERIALIZER += " }\n";
77
+
78
+ if (process.env["JSON_DEBUG"]) console.log(SERIALIZER);
79
+
80
+ const SERIALIZER_METHOD = SimpleParser.parseClassMember(SERIALIZER, node);
81
+
82
+ if (!node.members.find((v) => v.name.text == "__SERIALIZE_CUSTOM")) node.members.push(SERIALIZER_METHOD);
83
+ }
84
+
85
+ if (deserializers.length) {
86
+ const deserializer = deserializers[0];
87
+ if (!deserializer.signature.parameters.length) throwError("Could not find any parameters in custom deserializer for " + this.schema.name + ". Deserializers must have one parameter like 'deserializer(data: string): " + this.schema.name + " {}'", deserializer.range);
88
+ if (deserializer.signature.parameters.length > 1) throwError("Found too many parameters in custom deserializer for " + this.schema.name + ", but deserializers can only accept one parameter of type 'string'!", deserializer.signature.parameters[1].range);
89
+ if ((<NamedTypeNode>deserializer.signature.parameters[0].type).name.identifier.text != "string") throwError("Type of parameter for custom deserializer does not match! It must be 'string'", deserializer.signature.parameters[0].type.range);
90
+ if (!deserializer.signature.returnType || !((<NamedTypeNode>deserializer.signature.returnType).name.identifier.text.includes(this.schema.name) || (<NamedTypeNode>deserializer.signature.returnType).name.identifier.text.includes("this"))) throwError("Could not find valid return type for deserializer in " + this.schema.name + "!. Set the return type to type '" + this.schema.name + "' or 'this' and try again", deserializer.signature.returnType.range);
91
+
92
+ if (!deserializer.decorators.some((v) => (<IdentifierExpression>v.name).text == "inline")) {
93
+ deserializer.decorators.push(
94
+ Node.createDecorator(
95
+ Node.createIdentifierExpression(
96
+ "inline",
97
+ deserializer.range
98
+ ),
99
+ null,
100
+ deserializer.range
101
+ )
102
+ );
103
+ }
104
+ let DESERIALIZER = "";
105
+ DESERIALIZER += " @inline __DESERIALIZE_CUSTOM(data: string): " + this.schema.name + " {\n";
106
+ DESERIALIZER += " const d = this." + deserializer.name.text + "(data)";
107
+ DESERIALIZER += " if (isNullable(d) && changetype<usize>(d) == <usize>0) throw new Error(\"Could not deserialize data using custom deserializer!\");\n";
108
+ DESERIALIZER += " return d;\n";
109
+ DESERIALIZER += " }\n";
110
+
111
+ if (process.env["JSON_DEBUG"]) console.log(DESERIALIZER);
112
+
113
+ const DESERIALIZER_METHOD = SimpleParser.parseClassMember(DESERIALIZER, node);
114
+
115
+ if (!node.members.find((v) => v.name.text == "__DESERIALIZE_CUSTOM")) node.members.push(DESERIALIZER_METHOD);
116
+ }
44
117
 
45
118
  if (node.extendsType) {
46
119
  const extendsName = node.extendsType?.name.identifier.text;
@@ -77,15 +150,16 @@ class JSONTransform extends Visitor {
77
150
  return;
78
151
  }
79
152
 
80
- this.addRequiredImports(node);
153
+ this.addRequiredImports(node.range.source);
81
154
 
82
155
  for (const member of members) {
83
156
  if (!member.type) throwError("Fields must be strongly typed", node.range);
84
-
85
157
  const type = toString(member.type!);
86
158
  const name = member.name;
87
159
  const value = member.initializer ? toString(member.initializer!) : null;
88
160
 
161
+ // if (!this.isValidType(type, node)) throwError("Invalid Type. " + type + " is not a JSON-compatible type. Either decorate it with @omit, set it to private, or remove it.", member.type.range);
162
+
89
163
  if (type.startsWith("(") && type.includes("=>")) continue;
90
164
 
91
165
  const mem = new Property();
@@ -97,16 +171,15 @@ class JSONTransform extends Visitor {
97
171
 
98
172
  this.schema.byteSize += mem.byteSize;
99
173
 
100
- if (type.includes("JSON.Raw")) mem.flags.set(PropertyFlags.Raw, null);
101
-
102
174
  if (member.decorators) {
103
175
  for (const decorator of member.decorators) {
104
176
  const decoratorName = (decorator.name as IdentifierExpression).text.toLowerCase().trim();
105
177
  switch (decoratorName) {
106
178
  case "alias": {
107
- const args = getArgs(decorator.args);
108
- if (!args.length) throwError("@alias must have an argument of type string or number", member.range);
109
- mem.alias = args[0]!;
179
+ const arg = decorator.args[0];
180
+ if (!arg || arg.kind != NodeKind.Literal) throwError("@alias must have an argument of type string or number", member.range);
181
+ // @ts-ignore: exists
182
+ mem.alias = arg.value.toString();
110
183
  break;
111
184
  }
112
185
  case "omitif": {
@@ -178,7 +251,7 @@ class JSONTransform extends Visitor {
178
251
  INITIALIZE += ` this.${member.name} = changetype<nonnull<${member.type}>>(__new(offsetof<nonnull<${member.type}>>(), idof<nonnull<${member.type}>>())).__INITIALIZE();\n`;
179
252
  } else if (member.type.startsWith("Array<") || member.type.startsWith("Map<")) {
180
253
  INITIALIZE += ` this.${member.name} = [];\n`;
181
- } else if (member.type == "string" || member.type == "String" || member.type == "JSON.Raw") {
254
+ } else if (member.type == "string" || member.type == "String") {
182
255
  INITIALIZE += ` this.${member.name} = "";\n`;
183
256
  }
184
257
 
@@ -279,7 +352,7 @@ class JSONTransform extends Visitor {
279
352
  if (memberLen == 2) DESERIALIZE += `${indent}switch (load<u16>(keyStart)) {\n`;
280
353
  else if (memberLen == 4) DESERIALIZE += `${indent}switch (load<u32>(keyStart)) {\n`;
281
354
  else if (memberLen == 6) DESERIALIZE += `${indent}let code = load<u64>(keyStart) & 0x0000FFFFFFFFFFFF;\n`;
282
- else if (memberLen == 6) DESERIALIZE += `${indent}let code = load<u64>(keyStart);\n`;
355
+ else if (memberLen == 8) DESERIALIZE += `${indent}let code = load<u64>(keyStart);\n`;
283
356
  else DESERIALIZE += toMemCDecl(memberLen, indent);
284
357
  for (let i = 0; i < memberGroup.length; i++) {
285
358
  const member = memberGroup[i];
@@ -403,32 +476,22 @@ class JSONTransform extends Visitor {
403
476
  super.visitImportStatement(node);
404
477
  const source = this.parser.sources.find((src) => src.internalPath == node.internalPath);
405
478
  if (!source) return;
406
-
407
- if (source.statements.some((stmt) => stmt.kind === NodeKind.NamespaceDeclaration && (stmt as NamespaceDeclaration).name.text === "JSON")) this.imports.push(node);
479
+ this.imports.push(node);
408
480
  }
409
481
  visitSource(node: Source): void {
410
482
  this.imports = [];
411
483
  super.visitSource(node);
412
484
  }
413
- addRequiredImports(node: ClassDeclaration): void {
414
- // if (!this.imports.find((i) => i.declarations.find((d) => d.foreignName.text == "bs"))) {
415
- // if (!this.bsImport) {
416
- // this.bsImport = "import { bs } from \"as-bs\"";
417
- // if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + this.bsImport + "\n");
418
- // }
419
- // }
420
- if (!this.imports.find((i) => i.declarations.find((d) => d.foreignName.text == "bs"))) {
421
- const __filename = fileURLToPath(import.meta.url);
422
- const __dirname = path.dirname(__filename);
423
-
424
- let relativePath = path.relative(path.dirname(node.range.source.normalizedPath), path.resolve(__dirname, "../../modules/as-bs/"));
425
-
426
- if (!relativePath.startsWith(".") && !relativePath.startsWith("/")) relativePath = "./" + relativePath;
427
- // if (!existsSync(relativePath)) {
428
- // throw new Error("Could not find a valid json-as library to import from! Please add import { JSON } from \"path-to-json-as\"; in " + node.range.source.normalizedPath + "!");
429
- // }
430
-
431
- const txt = `import { bs } from "${relativePath}";`;
485
+ addRequiredImports(node: Source): void {
486
+ const bsImport = this.imports.find((i) => i.declarations.find((d) => d.foreignName.text == "bs"));
487
+ if (bsImport) {
488
+ const txt = `import { bs } from "as-bs";`;
489
+ if (!this.bsImport) {
490
+ this.bsImport = txt;
491
+ if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + txt + "\n");
492
+ }
493
+ } else {
494
+ const txt = `import { bs } from "as-bs";`;
432
495
  if (!this.bsImport) {
433
496
  this.bsImport = txt;
434
497
  if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + txt + "\n");
@@ -481,6 +544,48 @@ class JSONTransform extends Visitor {
481
544
  out.push("bs.offset += " + offset + ";");
482
545
  return out;
483
546
  }
547
+ isValidType(type: string, node: ClassDeclaration): boolean {
548
+ const validTypes = [
549
+ "string",
550
+ "u8",
551
+ "i8",
552
+ "u16",
553
+ "i16",
554
+ "u32",
555
+ "i32",
556
+ "u64",
557
+ "i64",
558
+ "f32",
559
+ "f64",
560
+ "bool",
561
+ "boolean",
562
+ "Date",
563
+ "JSON.Value",
564
+ "JSON.Obj",
565
+ "JSON.Raw",
566
+ "Value",
567
+ "Obj",
568
+ "Raw",
569
+ ...this.schemas.map((v) => v.name)
570
+ ];
571
+
572
+ const baseTypes = [
573
+ "Array",
574
+ "Map",
575
+ "Set",
576
+ "JSON.Box",
577
+ "Box"
578
+ ]
579
+
580
+ if (node && node.isGeneric && node.typeParameters) validTypes.push(...node.typeParameters.map((v) => v.name.text));
581
+ if (type.endsWith("| null")) {
582
+ if (isPrimitive(type.slice(0, type.indexOf("| null")))) return false;
583
+ return this.isValidType(type.slice(0, type.length - 7), node);
584
+ }
585
+ if (type.includes("<")) return baseTypes.includes(type.slice(0, type.indexOf("<"))) && this.isValidType(type.slice(type.indexOf("<") + 1, type.lastIndexOf(">")), node);
586
+ if (validTypes.includes(type)) return true;
587
+ return false;
588
+ }
484
589
  }
485
590
 
486
591
  export default class Transformer extends Transform {
@@ -505,6 +610,7 @@ export default class Transformer extends Transform {
505
610
  transformer.parser = parser;
506
611
  // Loop over every source
507
612
  for (const source of sources) {
613
+ // console.log("Source: " + source.normalizedPath);
508
614
  transformer.imports = [];
509
615
  transformer.currentSource = source;
510
616
  // Ignore all lib and std. Visit everything else.
@@ -560,29 +666,6 @@ function sortMembers(members: Property[]): Property[] {
560
666
  });
561
667
  }
562
668
 
563
- function getArgs(args: Expression[] | null): string[] {
564
- if (!args) return [];
565
- let out: string[] = [];
566
- for (const arg of args) {
567
- if (arg instanceof StringLiteralExpression) {
568
- out.push(arg.value);
569
- } else if (arg instanceof IntegerLiteralExpression) {
570
- out.push(i64_to_string(arg.value));
571
- } else if (arg instanceof FloatLiteralExpression) {
572
- out.push(arg.value.toString());
573
- } else if (arg instanceof NullExpression) {
574
- out.push(arg.text);
575
- } else if (arg instanceof TrueExpression) {
576
- out.push(arg.text);
577
- } else if (arg instanceof FalseExpression) {
578
- out.push(arg.text);
579
- } else if (arg instanceof IdentifierExpression) {
580
- out.push(arg.text);
581
- }
582
- }
583
- return out;
584
- }
585
-
586
669
  function toU16(data: string, offset: number = 0): string {
587
670
  return data.charCodeAt(offset + 0).toString();
588
671
  }
package/.gitmodules DELETED
File without changes
@@ -1,18 +0,0 @@
1
- {
2
- "input": ["./assembly/__tests__/string.spec.ts"],
3
- "outDir": "./build",
4
- "config": "none",
5
- "plugins": {
6
- "coverage": false
7
- },
8
- "buildOptions": {
9
- "args": ["--enable simd", "--runtime stub"],
10
- "target": "wasi"
11
- },
12
- "runOptions": {
13
- "runtime": {
14
- "name": "wasmtime",
15
- "run": "wasmtime <file>"
16
- }
17
- }
18
- }
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Jairus Tanaka <me@jairus.dev>
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,95 +0,0 @@
1
- <h5 align="center">
2
- <pre>
3
- <span style="font-size: 0.5em;">██████ ██ ██ ███████ ███████ ███████ ██████ ███████ ██ ███ ██ ██ ██
4
- ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
5
- ██████ ██ ██ █████ █████ █████ ██████ ███████ ██ ██ ██ ██ █████
6
- ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
7
- ██████ ██████ ██ ██ ███████ ██ ██ ███████ ██ ██ ████ ██ ██
8
- </span>
9
- AssemblyScript - v1.0.1
10
- </pre>
11
- </h5>
12
-
13
- ## About
14
-
15
- This library provides a centralized buffer for managing memory in AssemblyScript. It keeps track of a single buffer, the current offset, and handles allocations. Using a singular buffer essentially eliminates the need for any calls to `memory.copy()` as well as any `malloc()` or `realloc()`-type calls. Highly unsafe, but extremely useful for extraordinarily high-performance scenarios.
16
-
17
- [This library](https://github.com/JairusSW/as-bs) is what makes [as-json](https://github.com/JairusSW/as-json) operate in the multi-gigabyte-per-second ranges
18
-
19
- To take a look at some practical uses of as-bs, check out the functions [here](https://github.com/JairusSW/as-json/tree/master/assembly/serialize/simple)
20
-
21
- ## Installation
22
-
23
- ```bash
24
- npm install as-bs
25
- ```
26
-
27
- **🚨 IMPORTANT 🚨**
28
-
29
- To make sure we all depend on the same version of as-bs, please modify your package.json to meet the following
30
-
31
- Forgoing this will result in fragmentation and just a lot of problems.
32
-
33
- ```json
34
- "dependencies": {
35
- "as-bs": "latest"
36
- }
37
- ```
38
-
39
- ## Usage
40
-
41
- Here's an example taken out of [as-json](https://github.com/JairusSW/as-json/tree/master/assembly/serialize/simple/string.ts)
42
-
43
- This is an example of as-bs used right
44
-
45
- ```js
46
- import { bs } from "as-bs";
47
-
48
- function serializeString(src: string): string {
49
- const srcSize = bytes(src);
50
- bs.ensureSize(srcSize + 4);
51
-
52
- let srcPtr = changetype<usize>(src);
53
-
54
- const srcEnd = srcPtr + srcSize;
55
-
56
- store<u16>(bs.offset, QUOTE);
57
-
58
- bs.offset += 2;
59
-
60
- let lastPtr: i32 = srcPtr;
61
- while (srcPtr < srcEnd) {
62
- const code = load<u16>(srcPtr);
63
- if (code == 34 || code == 92 || code < 32) {
64
- const remBytes = srcPtr - lastPtr;
65
- memory.copy(bs.offset, lastPtr, remBytes);
66
- bs.offset += remBytes;
67
- const escaped = load<u32>(SERIALIZE_ESCAPE_TABLE + (code << 2));
68
- if ((escaped & 0xffff) != BACK_SLASH) {
69
- bs.ensureCapacity(12);
70
- store<u64>(bs.offset, 13511005048209500, 0);
71
- store<u32>(bs.offset, escaped, 8);
72
- bs.offset += 12;
73
- } else {
74
- bs.ensureCapacity(4);
75
- store<u32>(bs.offset, escaped, 0);
76
- bs.offset += 4;
77
- }
78
- lastPtr = srcPtr + 2;
79
- }
80
- srcPtr += 2;
81
- }
82
- const remBytes = srcEnd - lastPtr;
83
- memory.copy(bs.offset, lastPtr, remBytes);
84
- bs.offset += remBytes;
85
- store<u16>(bs.offset, QUOTE);
86
- bs.offset += 2;
87
- return bs.out<string>();
88
- }
89
- ```
90
-
91
- If you use this project in your codebase, consider dropping a [star](https://github.com/JairusSW/as-bs). I would really appreciate it!
92
-
93
- ## Issues
94
-
95
- Please submit an issue to https://github.com/JairusSW/as-bs/issues if you find anything wrong with this library
@@ -1,8 +0,0 @@
1
- export class SinkState {
2
- public offset: usize;
3
- public bufferSize: usize;
4
- public stackSize: usize;
5
- constructor() {
6
-
7
- }
8
- }
@@ -1,97 +0,0 @@
1
- {
2
- "extends": "assemblyscript/std/assembly.json",
3
- "include": ["./**/*.ts"],
4
- "compilerOptions": {
5
- /* Visit https://aka.ms/tsconfig to read more about this file */
6
- /* Projects */
7
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
8
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
9
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
10
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
11
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
12
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
13
- /* Language and Environment */
14
- "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- "experimentalDecorators": true /* Enable experimental support for TC39 stage 2 draft decorators. */,
18
- "emitDecoratorMetadata": true /* Emit design-type metadata for decorated declarations in source files. */,
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
- /* Modules */
27
- "module": "commonjs" /* Specify what module code is generated. */,
28
- // "rootDir": "./", /* Specify the root folder within your source files. */
29
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
34
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
37
- // "resolveJsonModule": true, /* Enable importing .json files. */
38
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
39
- /* JavaScript Support */
40
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
41
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
43
- /* Emit */
44
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
45
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
46
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
47
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
48
- // "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. */
49
- // "outDir": "./", /* Specify an output folder for all emitted files. */
50
- // "removeComments": true, /* Disable emitting comments. */
51
- // "noEmit": true, /* Disable emitting files from a compilation. */
52
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
53
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
54
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
55
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
56
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
57
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
58
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
59
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
60
- // "newLine": "crlf", /* Set the newline character for emitting files. */
61
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
62
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
63
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
64
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
65
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
66
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
67
- /* Interop Constraints */
68
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
69
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
70
- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
71
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
72
- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
73
- /* Type Checking */
74
- "strict": false /* Enable all strict type-checking options. */,
75
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
76
- "strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */,
77
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
78
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
79
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
80
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
81
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
82
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
83
- "noUnusedLocals": true /* Enable error reporting when local variables aren't read. */,
84
- "noUnusedParameters": true /* Raise an error when a function parameter isn't read. */,
85
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
86
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
87
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
88
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
89
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
90
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
91
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
92
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
93
- /* Completeness */
94
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
95
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
96
- }
97
- }
@@ -1 +0,0 @@
1
- export { bs } from "./assembly/index";
@@ -1,32 +0,0 @@
1
- {
2
- "name": "as-bs",
3
- "version": "1.0.1",
4
- "description": "Near zero-alloc centralized buffer for high performance applications",
5
- "types": "assembly/index.ts",
6
- "author": "Jairus Tanaka",
7
- "contributors": [],
8
- "license": "MIT",
9
- "scripts": {},
10
- "devDependencies": {
11
- "assemblyscript": "^0.27.31"
12
- },
13
- "dependencies": {},
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/JairusSW/as-bs.git"
17
- },
18
- "keywords": [
19
- "assemblyscript",
20
- "fast",
21
- "memory",
22
- "buffer"
23
- ],
24
- "bugs": {
25
- "url": "https://github.com/JairusSW/as-bs/issues"
26
- },
27
- "homepage": "https://github.com/JairusSW/as-bs#readme",
28
- "type": "module",
29
- "publishConfig": {
30
- "@JairusSW:registry": "https://npm.pkg.github.com"
31
- }
32
- }