json-as 1.0.0-alpha.1 → 1.0.0-alpha.3

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 (57) hide show
  1. package/.gitmodules +0 -0
  2. package/.prettierignore +6 -0
  3. package/.prettierrc.json +0 -1
  4. package/CHANGELOG +20 -1
  5. package/README.md +4 -3
  6. package/as-test.config.json +1 -1
  7. package/asconfig.json +1 -29
  8. package/assembly/__benches__/misc.bench.ts +0 -19
  9. package/assembly/__tests__/array.spec.ts +67 -0
  10. package/assembly/__tests__/bool.spec.ts +4 -12
  11. package/assembly/__tests__/float.spec.ts +11 -21
  12. package/assembly/__tests__/integer.spec.ts +7 -9
  13. package/assembly/__tests__/null.spec.ts +12 -0
  14. package/assembly/__tests__/obj.spec.ts +137 -3
  15. package/assembly/__tests__/simd/string.spec.ts +21 -21
  16. package/assembly/__tests__/string.spec.ts +6 -4
  17. package/assembly/__tests__/test.spec.ts +120 -191
  18. package/assembly/deserialize/simple/bool.ts +1 -1
  19. package/assembly/deserialize/simple/map.ts +1 -1
  20. package/assembly/deserialize/simple/object.ts +2 -3
  21. package/assembly/deserialize/simple/string.ts +4 -3
  22. package/assembly/globals/tables.ts +74 -416
  23. package/assembly/index.ts +20 -25
  24. package/assembly/serialize/simd/string.ts +11 -11
  25. package/assembly/serialize/simple/array.ts +5 -5
  26. package/assembly/serialize/simple/bool.ts +3 -3
  27. package/assembly/serialize/simple/date.ts +2 -2
  28. package/assembly/serialize/simple/float.ts +2 -2
  29. package/assembly/serialize/simple/integer.ts +2 -2
  30. package/assembly/serialize/simple/map.ts +7 -7
  31. package/assembly/serialize/simple/string.ts +5 -5
  32. package/assembly/test.ts +4 -48
  33. package/assembly/util/bytes.ts +1 -1
  34. package/modules/as-bs/LICENSE +21 -0
  35. package/modules/as-bs/README.md +95 -0
  36. package/modules/as-bs/assembly/index.ts +116 -0
  37. package/modules/as-bs/assembly/tsconfig.json +97 -0
  38. package/modules/as-bs/index.ts +1 -0
  39. package/modules/as-bs/package.json +32 -0
  40. package/modules/test/assembly/index.ts +22 -0
  41. package/package.json +5 -10
  42. package/run-tests.sh +15 -0
  43. package/transform/lib/builder.js +1262 -1340
  44. package/transform/lib/index.js +512 -572
  45. package/transform/lib/index.js.map +1 -1
  46. package/transform/lib/linker.js +10 -12
  47. package/transform/lib/types.js +19 -18
  48. package/transform/lib/types.js.map +1 -1
  49. package/transform/lib/util.js +34 -34
  50. package/transform/lib/visitor.js +526 -529
  51. package/transform/package.json +2 -1
  52. package/transform/src/index.ts +20 -9
  53. package/transform/src/types.ts +1 -0
  54. package/modules/bs/index.ts +0 -167
  55. package/modules/tsconfig.json +0 -8
  56. package/transform/lib/index.old.js +0 -404
  57. package/transform/lib/index.old.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { bs } from "../../../modules/bs";
1
+ import { bs } from "../../../modules/as-bs";
2
2
  import { COMMA, BRACKET_RIGHT, BRACKET_LEFT } from "../../custom/chars";
3
3
  import { JSON } from "../..";
4
4
 
@@ -6,12 +6,12 @@ export function serializeArray<T extends any[]>(src: T): void {
6
6
  const end = src.length - 1;
7
7
  let i = 0;
8
8
  if (end == -1) {
9
- bs.ensureSize(4);
9
+ bs.proposeSize(4);
10
10
  store<u32>(bs.offset, 6094939);
11
11
  bs.offset += 4;
12
12
  return;
13
13
  }
14
- bs.ensureSize(end << 3);
14
+ bs.proposeSize(end << 3);
15
15
 
16
16
  store<u16>(bs.offset, BRACKET_LEFT);
17
17
  bs.offset += 2;
@@ -19,14 +19,14 @@ export function serializeArray<T extends any[]>(src: T): void {
19
19
  while (i < end) {
20
20
  const block = unchecked(src[i++]);
21
21
  JSON.__serialize<valueof<T>>(block);
22
- bs.ensureSize(2);
22
+ bs.growSize(2);
23
23
  store<u16>(bs.offset, COMMA);
24
24
  bs.offset += 2;
25
25
  }
26
26
 
27
27
  const lastBlock = unchecked(src[end]);
28
28
  JSON.__serialize<valueof<T>>(lastBlock);
29
- bs.ensureSize(2);
29
+ bs.proposeSize(2);
30
30
  store<u16>(bs.offset, BRACKET_RIGHT);
31
31
  bs.offset += 2;
32
32
  }
@@ -1,4 +1,4 @@
1
- import { bs } from "../../../modules/bs";
1
+ import { bs } from "../../../modules/as-bs";
2
2
 
3
3
  /**
4
4
  * Serialize a bool to type string
@@ -7,11 +7,11 @@ import { bs } from "../../../modules/bs";
7
7
  */
8
8
  export function serializeBool(data: bool): void {
9
9
  if (data == true) {
10
- bs.ensureSize(8);
10
+ bs.proposeSize(8);
11
11
  store<u64>(bs.offset, 28429475166421108);
12
12
  bs.offset += 8;
13
13
  } else {
14
- bs.ensureSize(10);
14
+ bs.proposeSize(10);
15
15
  store<u64>(bs.offset, 32370086184550502);
16
16
  store<u64>(bs.offset, 101, 8);
17
17
  bs.offset += 10;
@@ -1,11 +1,11 @@
1
- import { bs } from "../../../modules/bs";
1
+ import { bs } from "../../../modules/as-bs";
2
2
  import { QUOTE } from "../../custom/chars";
3
3
  import { bytes } from "../../util/bytes";
4
4
 
5
5
  export function serializeDate(src: Date): void {
6
6
  const data = src.toISOString();
7
7
  const dataSize = bytes(data);
8
- bs.ensureSize(dataSize + 4);
8
+ bs.proposeSize(dataSize + 4);
9
9
  store<u16>(bs.offset, QUOTE);
10
10
  memory.copy(bs.offset + 2, changetype<usize>(data), dataSize);
11
11
  store<u16>(bs.offset + dataSize, QUOTE, 2);
@@ -1,7 +1,7 @@
1
1
  import { dtoa_buffered } from "util/number";
2
- import { bs } from "../../../modules/bs";
2
+ import { bs } from "../../../modules/as-bs";
3
3
 
4
4
  export function serializeFloat<T extends number>(data: T): void {
5
- bs.ensureSize(64);
5
+ bs.proposeSize(64);
6
6
  bs.offset += dtoa_buffered(bs.offset, data) << 1;
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import { itoa_buffered } from "util/number";
2
- import { bs } from "../../../modules/bs";
2
+ import { bs } from "../../../modules/as-bs";
3
3
 
4
4
  export function serializeInteger<T extends number>(data: T): void {
5
- bs.ensureSize(sizeof<T>() << 3);
5
+ bs.proposeSize(sizeof<T>() << 3);
6
6
  bs.offset += itoa_buffered(bs.offset, data) << 1;
7
7
  }
@@ -1,13 +1,13 @@
1
1
  import { JSON } from "../..";
2
2
  import { BRACE_LEFT, BRACE_RIGHT, COLON, COMMA } from "../../custom/chars";
3
- import { bs } from "../../../modules/bs";
3
+ import { bs } from "../../../modules/as-bs";
4
4
 
5
5
  export function serializeMap<T extends Map<any, any>>(src: T): void {
6
6
  const srcSize = src.size;
7
7
  const srcEnd = srcSize - 1;
8
8
 
9
9
  if (srcSize == 0) {
10
- bs.ensureSize(4);
10
+ bs.proposeSize(4);
11
11
  store<u32>(bs.offset, 8192123);
12
12
  bs.offset += 4;
13
13
  return;
@@ -16,28 +16,28 @@ export function serializeMap<T extends Map<any, any>>(src: T): void {
16
16
  let keys = src.keys();
17
17
  let values = src.values();
18
18
 
19
- bs.ensureSize(srcSize << 3); // This needs to be predicted better
19
+ bs.proposeSize(srcSize << 3); // This needs to be predicted better
20
20
 
21
21
  store<u16>(bs.offset, BRACE_LEFT);
22
22
  bs.offset += 2;
23
23
 
24
24
  for (let i = 0; i < srcEnd; i++) {
25
25
  JSON.__serialize(unchecked(keys[i]));
26
- bs.ensureSize(2);
26
+ bs.growSize(2);
27
27
  store<u16>(bs.offset, COLON);
28
28
  bs.offset += 2;
29
29
  JSON.__serialize(unchecked(values[i]));
30
- bs.ensureSize(2);
30
+ bs.growSize(2);
31
31
  store<u16>(bs.offset, COMMA);
32
32
  bs.offset += 2;
33
33
  }
34
34
 
35
35
  JSON.__serialize(unchecked(keys[srcEnd]));
36
- bs.ensureSize(2);
36
+ bs.growSize(2);
37
37
  store<u16>(bs.offset, COLON);
38
38
  bs.offset += 2;
39
39
  JSON.__serialize(unchecked(values[srcEnd]));
40
- bs.ensureSize(2);
40
+ bs.growSize(2);
41
41
  store<u16>(bs.offset, BRACE_RIGHT);
42
42
  bs.offset += 2;
43
43
  }
@@ -1,6 +1,6 @@
1
1
  import { _intTo16 } from "../../custom/util";
2
2
  import { bytes } from "../../util/bytes";
3
- import { bs } from "../../../modules/bs";
3
+ import { bs } from "../../../modules/as-bs";
4
4
  import { BACK_SLASH, QUOTE } from "../../custom/chars";
5
5
  import { SERIALIZE_ESCAPE_TABLE } from "../../globals/tables";
6
6
 
@@ -11,14 +11,14 @@ import { SERIALIZE_ESCAPE_TABLE } from "../../globals/tables";
11
11
  */
12
12
  export function serializeString(src: string): void {
13
13
  const srcSize = bytes(src);
14
- bs.ensureSize(srcSize + 4);
14
+ bs.proposeSize(srcSize + 4);
15
15
  let srcPtr = changetype<usize>(src);
16
16
  const srcEnd = srcPtr + srcSize;
17
17
 
18
18
  store<u16>(bs.offset, QUOTE);
19
19
  bs.offset += 2;
20
20
 
21
- let lastPtr: i32 = srcPtr;
21
+ let lastPtr: usize = srcPtr;
22
22
  while (srcPtr < srcEnd) {
23
23
  const code = load<u16>(srcPtr);
24
24
  if (code == 34 || code == 92 || code < 32) {
@@ -27,12 +27,12 @@ export function serializeString(src: string): void {
27
27
  bs.offset += remBytes;
28
28
  const escaped = load<u32>(SERIALIZE_ESCAPE_TABLE + (code << 2));
29
29
  if ((escaped & 0xffff) != BACK_SLASH) {
30
- bs.ensureSize(10);
30
+ bs.growSize(10);
31
31
  store<u64>(bs.offset, 13511005048209500, 0);
32
32
  store<u32>(bs.offset, escaped, 8);
33
33
  bs.offset += 12;
34
34
  } else {
35
- bs.ensureSize(2);
35
+ bs.growSize(2);
36
36
  store<u32>(bs.offset, escaped, 0);
37
37
  bs.offset += 4;
38
38
  }
package/assembly/test.ts CHANGED
@@ -1,49 +1,5 @@
1
- import { JSON } from ".";
2
- // @json or @serializable work here
3
- @json
4
- class Vec3 {
5
- x: f64 = 0.0;
6
- y: f64 = 0.0;
7
- z: f64 = 0.0;
8
- }
1
+ import { JSON } from "./";
2
+ import { describe, expect } from "../modules/test/assembly";
9
3
 
10
-
11
- @json
12
- class Player {
13
- // @alias("first name")
14
- firstName!: string;
15
- lastName!: string;
16
- lastActive!: i32[];
17
- // Drop in a code block, function, or expression that evaluates to a boolean
18
- @omitif((self: Player): boolean => self.age < 18)
19
- age!: i32;
20
- // @omitnull()
21
- pos!: Vec3 | null;
22
- isVerified!: boolean;
23
- @inline __INITIALIZE(): this {
24
- this.firstName = "";
25
- this.lastName = "";
26
- this.pos = changetype<nonnull<Vec3 | null>>(__new(offsetof<nonnull<Vec3 | null>>(), idof<nonnull<Vec3 | null>>())).__INITIALIZE();
27
- return this;
28
- }
29
- }
30
-
31
- const player: Player = {
32
- firstName: "Jairus",
33
- lastName: "Tanaka",
34
- lastActive: [1, 20, 2025],
35
- age: 18,
36
- pos: {
37
- x: 3.4,
38
- y: 1.2,
39
- z: 8.3,
40
- },
41
- isVerified: true,
42
- };
43
-
44
- const stringified = JSON.stringify<Player>(player);
45
- console.log("Serialized: " + stringified);
46
- const parsed = JSON.parse<Player>(stringified);
47
- console.log("Deserialized: " + JSON.stringify<Player>(parsed));
48
-
49
- console.log("Deserialized: " + JSON.stringify(JSON.parse<i32[]>("[1,2,3]")))
4
+ console.log(JSON.stringify(JSON.parse<string>('"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u000f\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f"')));
5
+ console.log('"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u000f\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f"');
@@ -7,6 +7,6 @@ import { OBJECT, TOTAL_OVERHEAD } from "rt/common";
7
7
  } else if (isManaged<T>() || isReference<T>()) {
8
8
  return changetype<OBJECT>(changetype<usize>(o) - TOTAL_OVERHEAD).rtSize;
9
9
  } else {
10
- ERROR("Cannot convert type " + nameof<T>() + " to bytes!");
10
+ throw new Error("Cannot convert type " + nameof<T>() + " to bytes!");
11
11
  }
12
12
  }
@@ -0,0 +1,21 @@
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.
@@ -0,0 +1,95 @@
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
@@ -0,0 +1,116 @@
1
+ import { OBJECT, TOTAL_OVERHEAD } from "rt/common";
2
+
3
+ /**
4
+ * Central buffer namespace for managing memory operations.
5
+ */
6
+ export namespace bs {
7
+ /** Current buffer pointer. */ // @ts-ignore
8
+ export let buffer: usize = __new(32, idof<ArrayBuffer>());
9
+
10
+ /** Current offset within the buffer. */
11
+ export let offset: usize = buffer;
12
+
13
+ /** Byte length of the buffer. */
14
+ export let byteLength: usize = 32;
15
+
16
+ /** Proposed size of output */
17
+ export let realSize: usize = offset;
18
+
19
+ /**
20
+ * Proposes that the buffer size is should be greater than or equal to the proposed size.
21
+ * If necessary, reallocates the buffer to the exact new size.
22
+ * @param size - The size to propose.
23
+ */
24
+ // @ts-ignore: Decorator valid here
25
+ @inline export function proposeSize(size: u32): void {
26
+ if ((realSize = size) > byteLength) {
27
+ byteLength = nextPowerOf2(size);
28
+ // @ts-ignore
29
+ const newPtr = __renew(buffer, byteLength);
30
+ offset = offset - buffer + newPtr;
31
+ buffer = newPtr;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Increases the proposed size by nextPowerOf2(n + 8) if necessary.
37
+ * If necessary, reallocates the buffer to the exact new size.
38
+ * @param size - The size to grow by.
39
+ */
40
+ // @ts-ignore: Decorator valid here
41
+ @inline export function growSize(size: u32): void {
42
+ realSize += size;
43
+ if (realSize > byteLength) {
44
+ byteLength += nextPowerOf2(size + 8);
45
+ // @ts-ignore
46
+ const newPtr = __renew(buffer, byteLength);
47
+ offset = offset - buffer + newPtr;
48
+ buffer = newPtr;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Resizes the buffer to the specified size.
54
+ * @param newSize - The new buffer size.
55
+ */
56
+ // @ts-ignore: Decorator valid here
57
+ @inline export function resize(newSize: u32): void {
58
+ // @ts-ignore
59
+ const newPtr = __renew(buffer, newSize);
60
+ byteLength = newSize;
61
+ buffer = newPtr;
62
+ offset = newPtr + newSize;
63
+ realSize = newPtr;
64
+ }
65
+
66
+ /**
67
+ * Copies the buffer's content to a new object of a specified type.
68
+ * @returns The new object containing the buffer's content.
69
+ */
70
+ // @ts-ignore: Decorator valid here
71
+ @inline export function out<T>(): T {
72
+ const len = offset - buffer;
73
+ // @ts-ignore
74
+ const _out = __new(len, idof<T>());
75
+ memory.copy(_out, buffer, len);
76
+
77
+ offset = buffer;
78
+ realSize = buffer;
79
+ return changetype<T>(_out);
80
+ }
81
+
82
+ /**
83
+ * Copies the buffer's content to a given destination pointer.
84
+ * Optionally shrinks the buffer after copying.
85
+ * @param dst - The destination pointer.
86
+ * @param s - Whether to shrink the buffer after copying.
87
+ * @returns The destination pointer cast to the specified type.
88
+ */
89
+ // @ts-ignore: Decorator valid here
90
+ @inline export function outTo<T>(dst: usize): T {
91
+ const len = offset - buffer;
92
+ // @ts-ignore
93
+ if (len != changetype<OBJECT>(dst - TOTAL_OVERHEAD).rtSize) __renew(len, idof<T>());
94
+ memory.copy(dst, buffer, len);
95
+
96
+ offset = buffer;
97
+ realSize = buffer;
98
+ return changetype<T>(dst);
99
+ }
100
+ }
101
+
102
+ // @ts-ignore: Decorator valid here
103
+ @inline function nextPowerOf2(n: u32): u32 {
104
+ return 1 << (32 - clz(n - 1));
105
+ }
106
+
107
+ // @ts-ignore: Decorator valid here
108
+ @inline function bytes<T>(o: T): i32 {
109
+ if (isInteger<T>() || isFloat<T>()) {
110
+ return sizeof<T>();
111
+ } else if (isManaged<T>() || isReference<T>()) {
112
+ return changetype<OBJECT>(changetype<usize>(o) - TOTAL_OVERHEAD).rtSize;
113
+ } else {
114
+ throw new Error("Cannot convert type " + nameof<T>() + " to bytes!");
115
+ }
116
+ }
@@ -0,0 +1,97 @@
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
+ }
@@ -0,0 +1 @@
1
+ export { bs } from "./assembly/index";
@@ -0,0 +1,32 @@
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
+ }
@@ -0,0 +1,22 @@
1
+ export function describe(description: string, routine: () => void): void {
2
+ routine();
3
+ }
4
+
5
+ export function expect(left: string): Expectation {
6
+ return new Expectation(left);
7
+ }
8
+
9
+ class Expectation {
10
+ public left: string;
11
+
12
+ constructor(left: string) {
13
+ this.left = left;
14
+ }
15
+ toBe(right: string): void {
16
+ if (this.left != right) {
17
+ console.log(" (expected) -> " + right);
18
+ console.log(" (received) -> " + this.left);
19
+ process.exit(1);
20
+ }
21
+ }
22
+ }