binary-packet 1.0.9 → 1.0.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.
package/README.md CHANGED
@@ -33,9 +33,11 @@ Currently, these kinds of `fields` are supported:
33
33
  | `Field.FLOAT_32` | 32 bits IEEE754 floating-point | | 4 |
34
34
  | `Field.FLOAT_64` | 64 bits IEEE754 floating-point | | 8 |
35
35
  | `BinaryPacket` | BinaryPacket "subpacket" | BinaryPacket | size(BinaryPacket) |
36
+ | `FieldString` | **ASCII** or **single octet utf-8 chars** string | Up to 65536 chars | 2 + length |
36
37
  | `FieldArray` | Dynamically-sized array of one of the types above | Up to 256 elements | 1 + length \* size(Element) |
37
38
  | `FieldFixedArray` | Statically-sized array of one of the types above | Any pre-defined numbers of elements | length \* size(Element) |
38
39
  | `FieldBitFlags` | Boolean flags packed into a single 8 bits integer | Up to 8 boolean flags | 1 |
40
+ | `FieldOptional` | Optional BinaryPacket "subpacket" | BinaryPacket \| undefined | 1 + size(BinaryPacket) |
39
41
 
40
42
  As shown, both arrays and nested objects ("subpackets") are supported. \
41
43
  Note: `FieldFixedArray` is much more memory efficient and performant than `FieldArray`, but require a pre-defined length.
@@ -153,16 +155,19 @@ So, take these "performance" comparisons with a grain of salt; or, even better,
153
155
 
154
156
  This library has been benchmarked against the following alternatives:
155
157
 
156
- - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular, fast and battle-tested library. Currently offers more features than binary-packet, but it appears to be 2x-4x slower in writes and 3x-10x slower in reads (depends on the packet structure) - is also less type-safe.
158
+ - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular, fast and battle-tested library. Currently offers more features than binary-packet, but it always appears to be slower and is also less type-safe.
157
159
  - [restructure](https://www.npmjs.com/package/restructure) - An older, popular schema-based library, has some extra features like LazyArrays, but it is **much slower** than both binary-packet and msgpackr. And, sadly, easily crashes with complex structures.
158
160
 
159
161
  The benchmarks are executed on three different kinds of packets:
160
162
 
161
163
  - EmptyPacket: basically an empty javascript object.
162
- - SimplePacket: objects with just primitive fields and statically-sized arrays.
163
- - ComplexPacket: objects with primitives, statically-sized arrays, dynamically-sized arrays, bitflags and other nested objects/arrays.
164
+ - SimplePacket: objects with just primitive fields, statically-sized arrays and a string.
165
+ - ComplexPacket: objects with primitives, statically-sized arrays, dynamically-sized arrays, bitflags, a string, an array of strings and other nested objects/arrays.
164
166
 
165
- You can see and run the benchmarks yourself if you clone the repository and launch `npm run benchmark`.
167
+ You can see and run the benchmarks yourself if you:
168
+
169
+ - Clone the [repository](https://github.com/silence-cloud-com/binary-packet).
170
+ - Launch `npm run benchmark`.
166
171
 
167
172
  ## Disclaimer
168
173
 
package/dist/index.d.mts CHANGED
@@ -5,6 +5,16 @@
5
5
  type TrueArrayBuffer = ArrayBuffer & {
6
6
  buffer?: undefined;
7
7
  };
8
+ declare global {
9
+ interface Buffer {
10
+ /**
11
+ * Node buffer's internals function. \
12
+ * For some reason it is not exposed through TypeScript. \
13
+ * Fastest way to write utf8 strings into buffers.
14
+ */
15
+ utf8Write(string: string, byteOffset?: number, byteLength?: number): number;
16
+ }
17
+ }
8
18
 
9
19
  declare const enum Field {
10
20
  /**
@@ -54,7 +64,7 @@ declare const enum Field {
54
64
  * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \
55
65
  * NOTE: As of now, dynamic arrays can have at most 256 elements.
56
66
  */
57
- declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T];
67
+ declare function FieldArray<T extends Field | BinaryPacket<Definition> | ''>(item: T): [itemType: T];
58
68
  /**
59
69
  * Defines a statically-sized array with elements of a certain type. \
60
70
  * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \
@@ -62,7 +72,7 @@ declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T)
62
72
  *
63
73
  * NOTE: If an array will not always have the same length, use the `FieldArray` type.
64
74
  */
65
- declare function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(item: T, length: Length): [itemType: T, length: Length];
75
+ declare function FieldFixedArray<T extends Field | BinaryPacket<Definition> | '', Length extends number>(item: T, length: Length): [itemType: T, length: Length];
66
76
  type BitFlags = (string[] | ReadonlyArray<string>) & {
67
77
  length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
68
78
  };
@@ -76,6 +86,20 @@ type BitFlags = (string[] | ReadonlyArray<string>) & {
76
86
  declare function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray): {
77
87
  flags: FlagsArray;
78
88
  };
89
+ /**
90
+ * Defines a string field. \
91
+ * Strings cannot be more than 65536 characters long.
92
+ *
93
+ * NOTE: Only strings containing just ASCII and/or single-octet UTF-8 characters are supported.
94
+ */
95
+ declare function FieldString(): "";
96
+ /**
97
+ * Defines an optional BinaryPacket "subpacket" field. \
98
+ * When writing and reading packets it'll be possible to provide and receive `undefined` instead of a valid object.
99
+ */
100
+ declare function FieldOptional<T extends BinaryPacket<Definition>>(packet: T): {
101
+ optional: T;
102
+ };
79
103
  /**
80
104
  * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \
81
105
  * Used in the `BinaryPacket::visit` static method to perform a sort of "pattern matching" on an incoming packet (of yet unknown type) buffer.
@@ -201,11 +225,13 @@ declare class BinaryPacket<T extends Definition> {
201
225
  */
202
226
  visitor(onVisit: (packet: ToJson<T>) => void): Visitor;
203
227
  private readonly entries;
228
+ readonly stringPositions: StringPositions;
204
229
  readonly minimumByteLength: number;
205
230
  private constructor();
206
231
  private static visit;
207
232
  private read;
208
233
  private write;
234
+ private precalculateBufferLengthWithStrings;
209
235
  }
210
236
  /**
211
237
  * BinaryPacket definition: \
@@ -251,8 +277,10 @@ declare class BinaryPacket<T extends Definition> {
251
277
  * // ...
252
278
  */
253
279
  type Definition = {
254
- [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>> | {
280
+ [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>> | MaybeArray<''> | {
255
281
  flags: BitFlags;
282
+ } | {
283
+ optional: BinaryPacket<Definition>;
256
284
  };
257
285
  };
258
286
  type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
@@ -263,13 +291,24 @@ type BitFlagsToJson<FlagsArray extends BitFlags> = {
263
291
  * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \
264
292
  */
265
293
  type ToJson<T extends Definition> = {
266
- [K in keyof T]: T[K] extends [infer Item] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends [infer Item, infer Length] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] & {
294
+ [K in keyof T]: T[K] extends [infer Item] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : Item extends '' ? string[] : number[] : T[K] extends [infer Item, infer Length] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] & {
295
+ length: Length;
296
+ } : Item extends '' ? string[] & {
267
297
  length: Length;
268
298
  } : number[] & {
269
299
  length: Length;
270
300
  } : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : T[K] extends {
271
301
  flags: infer FlagsArray extends BitFlags;
272
- } ? BitFlagsToJson<FlagsArray> : number;
302
+ } ? BitFlagsToJson<FlagsArray> : T[K] extends {
303
+ optional: BinaryPacket<infer BPDef extends Definition>;
304
+ } ? ToJson<BPDef> | undefined : T[K] extends '' ? string : number;
273
305
  };
306
+ type StringPositions = [
307
+ string[],
308
+ string[],
309
+ {
310
+ [field: string]: BinaryPacket<Definition>;
311
+ }
312
+ ];
274
313
 
275
- export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, type ToJson };
314
+ export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, FieldOptional, FieldString, type ToJson };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,16 @@
5
5
  type TrueArrayBuffer = ArrayBuffer & {
6
6
  buffer?: undefined;
7
7
  };
8
+ declare global {
9
+ interface Buffer {
10
+ /**
11
+ * Node buffer's internals function. \
12
+ * For some reason it is not exposed through TypeScript. \
13
+ * Fastest way to write utf8 strings into buffers.
14
+ */
15
+ utf8Write(string: string, byteOffset?: number, byteLength?: number): number;
16
+ }
17
+ }
8
18
 
9
19
  declare const enum Field {
10
20
  /**
@@ -54,7 +64,7 @@ declare const enum Field {
54
64
  * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \
55
65
  * NOTE: As of now, dynamic arrays can have at most 256 elements.
56
66
  */
57
- declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T];
67
+ declare function FieldArray<T extends Field | BinaryPacket<Definition> | ''>(item: T): [itemType: T];
58
68
  /**
59
69
  * Defines a statically-sized array with elements of a certain type. \
60
70
  * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \
@@ -62,7 +72,7 @@ declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T)
62
72
  *
63
73
  * NOTE: If an array will not always have the same length, use the `FieldArray` type.
64
74
  */
65
- declare function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(item: T, length: Length): [itemType: T, length: Length];
75
+ declare function FieldFixedArray<T extends Field | BinaryPacket<Definition> | '', Length extends number>(item: T, length: Length): [itemType: T, length: Length];
66
76
  type BitFlags = (string[] | ReadonlyArray<string>) & {
67
77
  length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
68
78
  };
@@ -76,6 +86,20 @@ type BitFlags = (string[] | ReadonlyArray<string>) & {
76
86
  declare function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray): {
77
87
  flags: FlagsArray;
78
88
  };
89
+ /**
90
+ * Defines a string field. \
91
+ * Strings cannot be more than 65536 characters long.
92
+ *
93
+ * NOTE: Only strings containing just ASCII and/or single-octet UTF-8 characters are supported.
94
+ */
95
+ declare function FieldString(): "";
96
+ /**
97
+ * Defines an optional BinaryPacket "subpacket" field. \
98
+ * When writing and reading packets it'll be possible to provide and receive `undefined` instead of a valid object.
99
+ */
100
+ declare function FieldOptional<T extends BinaryPacket<Definition>>(packet: T): {
101
+ optional: T;
102
+ };
79
103
  /**
80
104
  * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \
81
105
  * Used in the `BinaryPacket::visit` static method to perform a sort of "pattern matching" on an incoming packet (of yet unknown type) buffer.
@@ -201,11 +225,13 @@ declare class BinaryPacket<T extends Definition> {
201
225
  */
202
226
  visitor(onVisit: (packet: ToJson<T>) => void): Visitor;
203
227
  private readonly entries;
228
+ readonly stringPositions: StringPositions;
204
229
  readonly minimumByteLength: number;
205
230
  private constructor();
206
231
  private static visit;
207
232
  private read;
208
233
  private write;
234
+ private precalculateBufferLengthWithStrings;
209
235
  }
210
236
  /**
211
237
  * BinaryPacket definition: \
@@ -251,8 +277,10 @@ declare class BinaryPacket<T extends Definition> {
251
277
  * // ...
252
278
  */
253
279
  type Definition = {
254
- [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>> | {
280
+ [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>> | MaybeArray<''> | {
255
281
  flags: BitFlags;
282
+ } | {
283
+ optional: BinaryPacket<Definition>;
256
284
  };
257
285
  };
258
286
  type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
@@ -263,13 +291,24 @@ type BitFlagsToJson<FlagsArray extends BitFlags> = {
263
291
  * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \
264
292
  */
265
293
  type ToJson<T extends Definition> = {
266
- [K in keyof T]: T[K] extends [infer Item] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends [infer Item, infer Length] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] & {
294
+ [K in keyof T]: T[K] extends [infer Item] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : Item extends '' ? string[] : number[] : T[K] extends [infer Item, infer Length] ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] & {
295
+ length: Length;
296
+ } : Item extends '' ? string[] & {
267
297
  length: Length;
268
298
  } : number[] & {
269
299
  length: Length;
270
300
  } : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : T[K] extends {
271
301
  flags: infer FlagsArray extends BitFlags;
272
- } ? BitFlagsToJson<FlagsArray> : number;
302
+ } ? BitFlagsToJson<FlagsArray> : T[K] extends {
303
+ optional: BinaryPacket<infer BPDef extends Definition>;
304
+ } ? ToJson<BPDef> | undefined : T[K] extends '' ? string : number;
273
305
  };
306
+ type StringPositions = [
307
+ string[],
308
+ string[],
309
+ {
310
+ [field: string]: BinaryPacket<Definition>;
311
+ }
312
+ ];
274
313
 
275
- export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, type ToJson };
314
+ export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, FieldOptional, FieldString, type ToJson };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var D=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var L=(r,e)=>{for(var t in e)D(r,t,{get:e[t],enumerable:!0})},S=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of A(e))!b.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(i=U(e,n))||i.enumerable});return r};var G=r=>S(D({},"__esModule",{value:!0}),r);var J={};L(J,{BinaryPacket:()=>p,Field:()=>w,FieldArray:()=>v,FieldBitFlags:()=>k,FieldFixedArray:()=>V});module.exports=G(J);var c=typeof Buffer=="function";function h(r,e){let t=new ArrayBuffer(e),i=Math.min(r.byteLength,t.byteLength),n=Math.trunc(i/8);new Float64Array(t,0,n).set(new Float64Array(r.buffer,0,n));let a=n*8;return n=i-a,new Uint8Array(t,a,n).set(new Uint8Array(r.buffer,a,n)),new DataView(t)}function E(r,e){let t=Buffer.allocUnsafe(e);return r.copy(t),t}var w=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(w||{});function v(r){return[r]}function V(r,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[r,e]}function k(r){if(r.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${r.join(", ")}`);return{flags:r}}var p=class r{constructor(e,t){this.packetId=e;this.entries=t?O(t):[],this.minimumByteLength=x(this.entries).minimumByteLength}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new r(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return r.visit(e,m,t)}static visitDataView(e,...t){return r.visit(e,u,t)}static visitArrayBuffer(e,t,i,...n){return r.visit(new DataView(e,t,i),u,n)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,m)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,u)}readArrayBuffer(e,t,i){return this.read(c?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,c?m:u)}writeNodeBuffer(e){let t=Buffer.allocUnsafe(this.minimumByteLength);return this.write(t,e,{offset:0},this.minimumByteLength,this.minimumByteLength,I,E)}writeDataView(e){let t=new DataView(new ArrayBuffer(this.minimumByteLength));return this.write(t,e,{offset:0},this.minimumByteLength,this.minimumByteLength,_,h)}writeArrayBuffer(e){let t=c?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;minimumByteLength;static visit(e,t,i){for(let[n,a]of i)if(n.packetId===t[0](e,0))return a(n.read(e,{offset:0},e.byteLength,t))}read(e,t,i,n){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(n[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let a={};for(let[l,o]of this.entries)if(Array.isArray(o)){let s=o[1]??n[0](e,t.offset++),f=Array(s),d=o[0];if(typeof d=="object")for(let N=0;N<s;++N)f[N]=d.read(e,t,i,n);else{let N=T[d];for(let y=0;y<s;++y)f[y]=n[d](e,t.offset),t.offset+=N}a[l]=f}else if(typeof o=="number")a[l]=n[o](e,t.offset),t.offset+=T[o];else if("flags"in o){let s=n[0](e,t.offset);t.offset+=1,a[l]={};for(let f=0;f<o.flags.length;++f)a[l][o.flags[f]]=!!(s&1<<f)}else a[l]=o.read(e,t,i,n);return a}write(e,t,i,n,a,l,o){l[0](e,this.packetId,i.offset),i.offset+=1;for(let[s,f]of this.entries){let d=t[s];if(Array.isArray(f)){let N=d.length,y=f[1]===void 0;if(y&&(l[0](e,N,i.offset),i.offset+=1),N>0){let B=f[0];if(typeof B=="object"){if(y){let F=N*B.minimumByteLength;n+=F,a+=F,e.byteLength<a&&(e=o(e,a))}for(let F of d)e=B.write(e,F,i,n,a,l,o),n=i.offset,a=e.byteLength}else{let F=T[B];if(y){let g=N*F;n+=g,a+=g,e.byteLength<a&&(e=o(e,a))}for(let g of d)l[B](e,g,i.offset),i.offset+=F}}}else if(typeof f=="number")l[f](e,d,i.offset),i.offset+=T[f];else if("flags"in f){let N=0;for(let y=0;y<f.flags.length;++y)d[f.flags[y]]&&(N|=1<<y);l[0](e,N,i.offset),i.offset+=1}else e=f.write(e,d,i,n,a,l,o),n=i.offset,a=e.byteLength}return e}};function O(r){return Object.entries(r).sort(([e],[t])=>e.localeCompare(t))}function x(r){let e=1;for(let[,t]of r)if(Array.isArray(t))if(t.length===2){let i=typeof t[0]=="object"?t[0].minimumByteLength:T[t[0]];e+=t[1]*i}else e+=1;else t instanceof p?e+=t.minimumByteLength:typeof t=="object"?e+=1:e+=T[t];return{minimumByteLength:e}}var T=Array(8);T[0]=1;T[3]=1;T[1]=2;T[4]=2;T[2]=4;T[5]=4;T[6]=4;T[7]=8;var u=Array(8);u[0]=(r,e)=>r.getUint8(e);u[3]=(r,e)=>r.getInt8(e);u[1]=(r,e)=>r.getUint16(e);u[4]=(r,e)=>r.getInt16(e);u[2]=(r,e)=>r.getUint32(e);u[5]=(r,e)=>r.getInt32(e);u[6]=(r,e)=>r.getFloat32(e);u[7]=(r,e)=>r.getFloat64(e);var _=Array(8);_[0]=(r,e,t)=>r.setUint8(t,e);_[3]=(r,e,t)=>r.setInt8(t,e);_[1]=(r,e,t)=>r.setUint16(t,e);_[4]=(r,e,t)=>r.setInt16(t,e);_[2]=(r,e,t)=>r.setUint32(t,e);_[5]=(r,e,t)=>r.setInt32(t,e);_[6]=(r,e,t)=>r.setFloat32(t,e);_[7]=(r,e,t)=>r.setFloat64(t,e);var I=Array(8);c&&(I[0]=(r,e,t)=>r.writeUint8(e,t),I[3]=(r,e,t)=>r.writeInt8(e,t),I[1]=(r,e,t)=>r.writeUint16LE(e,t),I[4]=(r,e,t)=>r.writeInt16LE(e,t),I[2]=(r,e,t)=>r.writeUint32LE(e,t),I[5]=(r,e,t)=>r.writeInt32LE(e,t),I[6]=(r,e,t)=>r.writeFloatLE(e,t),I[7]=(r,e,t)=>r.writeDoubleLE(e,t));var m=Array(8);c&&(m[0]=(r,e)=>r.readUint8(e),m[3]=(r,e)=>r.readInt8(e),m[1]=(r,e)=>r.readUint16LE(e),m[4]=(r,e)=>r.readInt16LE(e),m[2]=(r,e)=>r.readUint32LE(e),m[5]=(r,e)=>r.readInt32LE(e),m[6]=(r,e)=>r.readFloatLE(e),m[7]=(r,e)=>r.readDoubleLE(e));0&&(module.exports={BinaryPacket,Field,FieldArray,FieldBitFlags,FieldFixedArray});
1
+ "use strict";var U=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var O=(n,e)=>{for(var t in e)U(n,t,{get:e[t],enumerable:!0})},J=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of k(e))!v.call(n,r)&&r!==t&&U(n,r,{get:()=>e[r],enumerable:!(i=V(e,r))||i.enumerable});return n};var C=n=>J(U({},"__esModule",{value:!0}),n);var q={};O(q,{BinaryPacket:()=>F,Field:()=>x,FieldArray:()=>R,FieldBitFlags:()=>W,FieldFixedArray:()=>M,FieldOptional:()=>z,FieldString:()=>$});module.exports=C(q);var D=typeof Buffer=="function";function b(n,e){let t=new ArrayBuffer(e),i=Math.min(n.byteLength,t.byteLength),r=Math.trunc(i/8);new Float64Array(t,0,r).set(new Float64Array(n.buffer,0,r));let a=r*8;return r=i-a,new Uint8Array(t,a,r).set(new Uint8Array(n.buffer,a,r)),new DataView(t)}function A(n,e){let t=Buffer.allocUnsafe(e);return n.copy(t),t}var j=new TextEncoder,K=new TextDecoder;function S(n,e,t){let i=t.length,r=new Uint8Array(n.buffer,n.byteOffset+e,i);i<=64?G(r,0,t,i):j.encodeInto(t,r)}function L(n,e,t){let i=t.length;i<=64?G(n,e,t,i):n.utf8Write(t,e,i)}function G(n,e,t,i){for(let r=0;r<i;++r)n[e+r]=t.charCodeAt(r)&255}function E(n,e,t){return n.subarray(e,e+t).toString("utf8")}function h(n,e,t){return K.decode(new DataView(n.buffer,n.byteOffset+e,t))}var x=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(x||{});function R(n){return[n]}function M(n,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[n,e]}function W(n){if(n.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${n.join(", ")}`);return{flags:n}}function $(){return""}function z(n){return{optional:n}}var F=class n{constructor(e,t){this.packetId=e;this.entries=t?Y(t):[];let i=Z(this.entries);this.minimumByteLength=i.minimumByteLength,this.stringPositions=i.stringPositions}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new n(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return n.visit(e,I,E,t)}static visitDataView(e,...t){return n.visit(e,g,h,t)}static visitArrayBuffer(e,t,i,...r){return n.visit(new DataView(e,t,i),g,h,r)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,I,E)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,g,h)}readArrayBuffer(e,t,i){return this.read(D?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,D?I:g,D?E:h)}writeNodeBuffer(e){let t=this.precalculateBufferLengthWithStrings(e),i=Buffer.allocUnsafe(t);return this.write(i,e,{offset:0},t,t,c,A,L)}writeDataView(e){let t=this.precalculateBufferLengthWithStrings(e),i=new DataView(new ArrayBuffer(t));return this.write(i,e,{offset:0},t,t,_,b,S)}writeArrayBuffer(e){let t=D?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;stringPositions;minimumByteLength;static visit(e,t,i,r){for(let[a,o]of r)if(a.packetId===t[0](e,0))return o(a.read(e,{offset:0},e.byteLength,t,i))}read(e,t,i,r,a){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(r[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let o={};for(let[u,s]of this.entries)if(Array.isArray(s)){let d=s[1]??r[0](e,t.offset++),f=Array(d),T=s[0];if(typeof T=="object")for(let l=0;l<d;++l)f[l]=T.read(e,t,i,r,a);else if(T==="")for(let l=0;l<d;++l){let N=r[1](e,t.offset);t.offset+=2,f[l]=a(e,t.offset,N),t.offset+=N}else{let l=y[T];for(let N=0;N<d;++N)f[N]=r[T](e,t.offset),t.offset+=l}o[u]=f}else if(typeof s=="number")o[u]=r[s](e,t.offset),t.offset+=y[s];else if(s===""){let d=r[1](e,t.offset);t.offset+=2,o[u]=a(e,t.offset,d),t.offset+=d}else if("flags"in s){let d=r[0](e,t.offset);t.offset+=1,o[u]={};for(let f=0;f<s.flags.length;++f)o[u][s.flags[f]]=!!(d&1<<f)}else if("optional"in s){let d=r[0](e,t.offset)!==0;t.offset+=1,d&&(o[u]=s.optional.read(e,t,i,r,a))}else o[u]=s.read(e,t,i,r,a);return o}write(e,t,i,r,a,o,u,s){o[0](e,this.packetId,i.offset),i.offset+=1;for(let[d,f]of this.entries){let T=t[d];if(Array.isArray(f)){let l=T.length,N=f[1]===void 0;if(N&&(o[0](e,l,i.offset),i.offset+=1),l>0){let B=f[0];if(typeof B=="object"){if(N){let m=l*B.minimumByteLength;r+=m,a+=m,e.byteLength<a&&(e=u(e,a))}for(let m of T)e=B.write(e,m,i,r,a,o,u,s),r=i.offset,a=e.byteLength}else if(B==="")for(let m=0;m<l;++m){let p=T[m],w=p.length;o[1](e,w,i.offset),i.offset+=2,s(e,i.offset,p),i.offset+=w}else{let m=y[B];if(N){let p=l*m;r+=p,a+=p,e.byteLength<a&&(e=u(e,a))}for(let p of T)o[B](e,p,i.offset),i.offset+=m}}}else if(typeof f=="number")o[f](e,T,i.offset),i.offset+=y[f];else if(f===""){let l=T.length;o[1](e,l,i.offset),i.offset+=2,s(e,i.offset,T),i.offset+=l}else if("flags"in f){let l=0;for(let N=0;N<f.flags.length;++N)T[f.flags[N]]&&(l|=1<<N);o[0](e,l,i.offset),i.offset+=1}else"optional"in f?T?(o[0](e,1,i.offset),i.offset+=1,r+=f.optional.minimumByteLength,a+=f.optional.minimumByteLength,e.byteLength<a&&(e=u(e,a)),e=f.optional.write(e,T,i,r,a,o,u,s),r=i.offset,a=e.byteLength):(o[0](e,0,i.offset),i.offset+=1):(e=f.write(e,T,i,r,a,o,u,s),r=i.offset,a=e.byteLength)}return e}precalculateBufferLengthWithStrings(e){let t=this.minimumByteLength;for(let i of this.stringPositions[0])t+=e[i].length;for(let i of this.stringPositions[1])for(let r of e[i])t+=2+r.length;for(let i in this.stringPositions[2])t+=this.stringPositions[2][i].precalculateBufferLengthWithStrings(e[i]);return t}};function Y(n){return Object.entries(n).sort(([e],[t])=>e.localeCompare(t))}function Z(n){let e=1,t=[[],[],{}];for(let[i,r]of n)if(Array.isArray(r))if(r.length===2){let a=r[0]==="",o=typeof r[0]=="object"?r[0].minimumByteLength:a?2:y[r[0]];e+=r[1]*o,a&&t[1].push(i)}else e+=1,r[0]===""&&t[1].push(i);else r instanceof F?(e+=r.minimumByteLength,t[2][i]=r):typeof r=="object"?e+=1:r===""?(e+=2,t[0].push(i)):e+=y[r];return{minimumByteLength:e,stringPositions:t}}var y=Array(8);y[0]=1;y[3]=1;y[1]=2;y[4]=2;y[2]=4;y[5]=4;y[6]=4;y[7]=8;var g=Array(8);g[0]=(n,e)=>n.getUint8(e);g[3]=(n,e)=>n.getInt8(e);g[1]=(n,e)=>n.getUint16(e);g[4]=(n,e)=>n.getInt16(e);g[2]=(n,e)=>n.getUint32(e);g[5]=(n,e)=>n.getInt32(e);g[6]=(n,e)=>n.getFloat32(e);g[7]=(n,e)=>n.getFloat64(e);var _=Array(8);_[0]=(n,e,t)=>n.setUint8(t,e);_[3]=(n,e,t)=>n.setInt8(t,e);_[1]=(n,e,t)=>n.setUint16(t,e);_[4]=(n,e,t)=>n.setInt16(t,e);_[2]=(n,e,t)=>n.setUint32(t,e);_[5]=(n,e,t)=>n.setInt32(t,e);_[6]=(n,e,t)=>n.setFloat32(t,e);_[7]=(n,e,t)=>n.setFloat64(t,e);var c=Array(8);D&&(c[0]=(n,e,t)=>n.writeUint8(e,t),c[3]=(n,e,t)=>n.writeInt8(e,t),c[1]=(n,e,t)=>n.writeUint16LE(e,t),c[4]=(n,e,t)=>n.writeInt16LE(e,t),c[2]=(n,e,t)=>n.writeUint32LE(e,t),c[5]=(n,e,t)=>n.writeInt32LE(e,t),c[6]=(n,e,t)=>n.writeFloatLE(e,t),c[7]=(n,e,t)=>n.writeDoubleLE(e,t));var I=Array(8);D&&(I[0]=(n,e)=>n.readUint8(e),I[3]=(n,e)=>n.readInt8(e),I[1]=(n,e)=>n.readUint16LE(e),I[4]=(n,e)=>n.readInt16LE(e),I[2]=(n,e)=>n.readUint32LE(e),I[5]=(n,e)=>n.readInt32LE(e),I[6]=(n,e)=>n.readFloatLE(e),I[7]=(n,e)=>n.readDoubleLE(e));0&&(module.exports={BinaryPacket,Field,FieldArray,FieldBitFlags,FieldFixedArray,FieldOptional,FieldString});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/buffers.ts"],"sourcesContent":["import { growDataView, growNodeBuffer, hasNodeBuffers, type TrueArrayBuffer } from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION_BUF)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : new DataView(dataIn, byteOffset, byteLength),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const buffer = Buffer.allocUnsafe(this.minimumByteLength)\r\n\r\n return this.write(\r\n buffer,\r\n dataOut,\r\n { offset: 0 },\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n SET_FUNCTION_BUF,\r\n growNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a DataView. \\\r\n */\r\n writeDataView(dataOut: ToJson<T>) {\r\n const dataview = new DataView(new ArrayBuffer(this.minimumByteLength))\r\n\r\n return this.write(\r\n dataview,\r\n dataOut,\r\n { offset: 0 },\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n SET_FUNCTION,\r\n growDataView\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into an ArrayBuffer. \\\r\n * This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \\\r\n *\r\n * This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \\\r\n * Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \\\r\n *\r\n * Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \\\r\n * For more information read the `readArrayBuffer` documentation.\r\n */\r\n writeArrayBuffer(dataOut: ToJson<T>) {\r\n const buf = hasNodeBuffers ? this.writeNodeBuffer(dataOut) : this.writeDataView(dataOut)\r\n return { buffer: buf.buffer, byteLength: buf.byteLength, byteOffset: buf.byteOffset }\r\n }\r\n\r\n /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly minimumByteLength: number\r\n\r\n private constructor(\r\n private readonly packetId: number,\r\n definition?: T\r\n ) {\r\n this.entries = definition ? sortEntries(definition) : []\r\n this.minimumByteLength = inspectEntries(this.entries).minimumByteLength\r\n }\r\n\r\n private static visit(\r\n dataIn: Buffer | DataView,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions))\r\n }\r\n }\r\n }\r\n\r\n private read(\r\n dataIn: DataView | Buffer,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n maxByteLength: number,\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF,\r\n growBufferFunction: (buffer: Buf, newByteLength: number) => Buf\r\n ): Buf {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, this.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n for (const [name, def] of this.entries) {\r\n const data = dataOut[name]\r\n\r\n if (Array.isArray(def)) {\r\n // Could be both an array of just numbers or \"subpackets\"\r\n\r\n const length = (data as any[]).length\r\n\r\n // Check if it is a dynamically-sized array, if it is, the length of the array must be serialized in the buffer before its elements\r\n // Explicitly check for undefined and not falsy values because it could be a statically-sized array of 0 elements.\r\n const isDynamicArray = def[1] === undefined\r\n\r\n if (isDynamicArray) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n\r\n if (length > 0) {\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemType.minimumByteLength\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n for (const object of data as unknown as ToJson<Definition>[]) {\r\n buffer = itemType.write(\r\n buffer,\r\n object,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemSize\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (const number of data as number[]) {\r\n writeFunctions[itemType](buffer as any, number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n buffer = def.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n\r\n for (const [, type] of entries) {\r\n if (Array.isArray(type)) {\r\n if (type.length === 2) {\r\n // Statically-sized array\r\n const itemSize =\r\n typeof type[0] === 'object' ? type[0].minimumByteLength : BYTE_SIZE[type[0]]\r\n\r\n minimumByteLength += type[1] * itemSize\r\n } else {\r\n // Dynamically-sized array\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n } else if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength }\r\n}\r\n\r\n//////////////////////////////////////////////\r\n// The logic here is practically over //\r\n// Here below there are needed constants //\r\n// that map a field-type to a functionality //\r\n//////////////////////////////////////////////\r\n\r\nconst BYTE_SIZE = Array(8) as number[]\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_8] = 1\r\nBYTE_SIZE[Field.INT_8] = 1\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_16] = 2\r\nBYTE_SIZE[Field.INT_16] = 2\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_32] = 4\r\nBYTE_SIZE[Field.INT_32] = 4\r\nBYTE_SIZE[Field.FLOAT_32] = 4\r\n\r\nBYTE_SIZE[Field.FLOAT_64] = 8\r\n\r\nconst GET_FUNCTION = Array(8) as ((view: DataView, offset: number) => number)[]\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_8] = (view, offset) => view.getUint8(offset)\r\nGET_FUNCTION[Field.INT_8] = (view, offset) => view.getInt8(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_16] = (view, offset) => view.getUint16(offset)\r\nGET_FUNCTION[Field.INT_16] = (view, offset) => view.getInt16(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset) => view.getUint32(offset)\r\nGET_FUNCTION[Field.INT_32] = (view, offset) => view.getInt32(offset)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset) => view.getFloat32(offset)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset) => view.getFloat64(offset)\r\n\r\nconst SET_FUNCTION = Array(8) as ((view: DataView, value: number, offset: number) => void)[]\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_8] = (view, value, offset) => view.setUint8(offset, value)\r\nSET_FUNCTION[Field.INT_8] = (view, value, offset) => view.setInt8(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_16] = (view, value, offset) => view.setUint16(offset, value)\r\nSET_FUNCTION[Field.INT_16] = (view, value, offset) => view.setInt16(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_32] = (view, value, offset) => view.setUint32(offset, value)\r\nSET_FUNCTION[Field.INT_32] = (view, value, offset) => view.setInt32(offset, value)\r\nSET_FUNCTION[Field.FLOAT_32] = (view, value, offset) => view.setFloat32(offset, value)\r\n\r\nSET_FUNCTION[Field.FLOAT_64] = (view, value, offset) => view.setFloat64(offset, value)\r\n\r\nconst SET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, value: number, offset: number) => void)[]\r\n\r\nif (hasNodeBuffers) {\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, value, offset) => view.writeUint8(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_8] = (view, value, offset) => view.writeInt8(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, value, offset) =>\r\n view.writeUint16LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_16] = (view, value, offset) => view.writeInt16LE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, value, offset) =>\r\n view.writeUint32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_32] = (view, value, offset) => view.writeInt32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.FLOAT_32] = (view, value, offset) => view.writeFloatLE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.FLOAT_64] = (view, value, offset) => view.writeDoubleLE(value, offset)\r\n}\r\n\r\nconst GET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, offset: number) => number)[]\r\n\r\nif (hasNodeBuffers) {\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, offset) => view.readUint8(offset)\r\n GET_FUNCTION_BUF[Field.INT_8] = (view, offset) => view.readInt8(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, offset) => view.readUint16LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_16] = (view, offset) => view.readInt16LE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, offset) => view.readUint32LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_32] = (view, offset) => view.readInt32LE(offset)\r\n GET_FUNCTION_BUF[Field.FLOAT_32] = (view, offset) => view.readFloatLE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.FLOAT_64] = (view, offset) => view.readDoubleLE(offset)\r\n}\r\n","/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,UAAAC,EAAA,eAAAC,EAAA,kBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCMO,IAAMQ,EAAiB,OAAO,QAAW,WAEzC,SAASC,EAAaC,EAAoBC,EAAuB,CACtE,IAAMC,EAAgB,IAAI,YAAYD,CAAa,EAC7CE,EAAe,KAAK,IAAIH,EAAS,WAAYE,EAAc,UAAU,EAGvEE,EAAS,KAAK,MAAMD,EAAe,CAAC,EACxC,IAAI,aAAaD,EAAe,EAAGE,CAAM,EAAE,IAA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ClC/B,EAAiB,CAAY,EAAI,CAAC8B,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EAEzF/B,EAAiB,CAAqB,EAAI,CAAC8B,EAAME,EAAOD,IACtDD,EAAK,cAAcE,EAAOD,CAAM,EAClC/B,EAAiB,CAAY,EAAI,CAAC8B,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EACzF/B,EAAiB,CAAc,EAAI,CAAC8B,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EAE3F/B,EAAiB,CAAc,EAAI,CAAC8B,EAAME,EAAOD,IAAWD,EAAK,cAAcE,EAAOD,CAAM,GAG9F,IAAMtC,EAAmB,MAAM,CAAC,EAE5BK,IACFL,EAAiB,CAAoB,EAAI,CAACqC,EAAMC,IAAWD,EAAK,UAAUC,CAAM,EAChFtC,EAAiB,CAAW,EAAI,CAACqC,EAAMC,IAAWD,EAAK,SAASC,CAAM,EAEtEtC,EAAiB,CAAqB,EAAI,CAACqC,EAAMC,IAAWD,EAAK,aAAaC,CAAM,EACpFtC,EAAiB,CAAY,EAAI,CAACqC,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAE1EtC,EAAiB,CAAqB,EAAI,CAACqC,EAAMC,IAAWD,EAAK,aAAaC,CAAM,EACpFtC,EAAiB,CAAY,EAAI,CAACqC,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAC1EtC,EAAiB,CAAc,EAAI,CAACqC,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAE5EtC,EAAiB,CAAc,EAAI,CAACqC,EAAMC,IAAWD,EAAK,aAAaC,CAAM","names":["src_exports","__export","BinaryPacket","Field","FieldArray","FieldBitFlags","FieldFixedArray","__toCommonJS","hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","GET_FUNCTION","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","onVisit","readFunctions","Packet","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","maxByteLength","writeFunctions","growBufferFunction","data","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","type","view","offset","value"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/buffers.ts"],"sourcesContent":["import {\r\n decodeStringFromDataView,\r\n decodeStringFromNodeBuffer,\r\n encodeStringIntoDataView,\r\n encodeStringIntoNodeBuffer,\r\n growDataView,\r\n growNodeBuffer,\r\n hasNodeBuffers,\r\n type TrueArrayBuffer\r\n} from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition> | ''>(\r\n item: T\r\n): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<\r\n T extends Field | BinaryPacket<Definition> | '',\r\n Length extends number\r\n>(item: T, length: Length): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Defines a string field. \\\r\n * Strings cannot be more than 65536 characters long.\r\n *\r\n * NOTE: Only strings containing just ASCII and/or single-octet UTF-8 characters are supported.\r\n */\r\nexport function FieldString() {\r\n return '' as const\r\n}\r\n\r\n/**\r\n * Defines an optional BinaryPacket \"subpacket\" field. \\\r\n * When writing and reading packets it'll be possible to provide and receive `undefined` instead of a valid object.\r\n */\r\nexport function FieldOptional<T extends BinaryPacket<Definition>>(packet: T) {\r\n return { optional: packet }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, decodeStringFromNodeBuffer, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, decodeStringFromDataView, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n decodeStringFromDataView,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n GET_FUNCTION_BUF,\r\n decodeStringFromNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION, decodeStringFromDataView)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : (new DataView(dataIn, byteOffset, byteLength) as any),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION,\r\n hasNodeBuffers ? decodeStringFromNodeBuffer : (decodeStringFromDataView as any)\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const byteLength = this.precalculateBufferLengthWithStrings(dataOut)\r\n const buffer = Buffer.allocUnsafe(byteLength)\r\n\r\n return this.write(\r\n buffer,\r\n dataOut,\r\n { offset: 0 },\r\n byteLength,\r\n byteLength,\r\n SET_FUNCTION_BUF,\r\n growNodeBuffer,\r\n encodeStringIntoNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a DataView. \\\r\n */\r\n writeDataView(dataOut: ToJson<T>) {\r\n const byteLength = this.precalculateBufferLengthWithStrings(dataOut)\r\n const dataview = new DataView(new ArrayBuffer(byteLength))\r\n\r\n return this.write(\r\n dataview,\r\n dataOut,\r\n { offset: 0 },\r\n byteLength,\r\n byteLength,\r\n SET_FUNCTION,\r\n growDataView,\r\n encodeStringIntoDataView\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into an ArrayBuffer. \\\r\n * This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \\\r\n *\r\n * This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \\\r\n * Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \\\r\n *\r\n * Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \\\r\n * For more information read the `readArrayBuffer` documentation.\r\n */\r\n writeArrayBuffer(dataOut: ToJson<T>) {\r\n const buf = hasNodeBuffers ? this.writeNodeBuffer(dataOut) : this.writeDataView(dataOut)\r\n return { buffer: buf.buffer, byteLength: buf.byteLength, byteOffset: buf.byteOffset }\r\n }\r\n\r\n /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly stringPositions: StringPositions\r\n readonly minimumByteLength: number\r\n\r\n private constructor(\r\n private readonly packetId: number,\r\n definition?: T\r\n ) {\r\n this.entries = definition ? sortEntries(definition) : []\r\n const inspection = inspectEntries(this.entries)\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.stringPositions = inspection.stringPositions\r\n }\r\n\r\n private static visit<Buf extends DataView | Buffer>(\r\n dataIn: Buf,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n decodeStringFunction: (dataIn: Buf, byteOffset: number, strlen: number) => string,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(\r\n Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions, decodeStringFunction)\r\n )\r\n }\r\n }\r\n }\r\n\r\n private read<Buf extends DataView | Buffer>(\r\n dataIn: Buf,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n decodeStringFunction: (dataIn: Buf, byteOffset: number, strlen: number) => string\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n } else if (itemType === '') {\r\n // Array of strings\r\n for (let i = 0; i < length; ++i) {\r\n const strlen = readFunctions[Field.UNSIGNED_INT_16](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n array[i] = decodeStringFunction(dataIn, offsetPointer.offset, strlen)\r\n offsetPointer.offset += strlen\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if (def === '') {\r\n const strlen = readFunctions[Field.UNSIGNED_INT_16](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = decodeStringFunction(dataIn, offsetPointer.offset, strlen)\r\n offsetPointer.offset += strlen\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else if ('optional' in def) {\r\n // Single optional \"subpacket\"\r\n const hasSubPacket =\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== 0\r\n\r\n offsetPointer.offset += 1\r\n\r\n if (hasSubPacket) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.optional.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n maxByteLength: number,\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF,\r\n growBufferFunction: (buffer: Buf, newByteLength: number) => Buf,\r\n encodeStringFunction: (buffer: Buf, byteOffset: number, string: string) => void\r\n ): Buf {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, this.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n for (const [name, def] of this.entries) {\r\n const data = dataOut[name]\r\n\r\n if (Array.isArray(def)) {\r\n // Could be both an array of just numbers or \"subpackets\"\r\n\r\n const length = (data as any[]).length\r\n\r\n // Check if it is a dynamically-sized array, if it is, the length of the array must be serialized in the buffer before its elements\r\n // Explicitly check for undefined and not falsy values because it could be a statically-sized array of 0 elements.\r\n const isDynamicArray = def[1] === undefined\r\n\r\n if (isDynamicArray) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n\r\n if (length > 0) {\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemType.minimumByteLength\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n for (const object of data as unknown as ToJson<Definition>[]) {\r\n // Array of \"subpackets\"\r\n buffer = itemType.write(\r\n buffer,\r\n object,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n } else if (itemType === '') {\r\n // Array of strings\r\n for (let i = 0; i < length; ++i) {\r\n const str = (data as unknown as string[])[i]\r\n const strlen = str.length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_16](buffer as any, strlen, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n encodeStringFunction(buffer, offsetPointer.offset, str)\r\n offsetPointer.offset += strlen\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemSize\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (const number of data as number[]) {\r\n writeFunctions[itemType](buffer as any, number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if (def === '') {\r\n // String\r\n const strlen = (data as string).length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_16](buffer as any, strlen, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n encodeStringFunction(buffer, offsetPointer.offset, data as string)\r\n offsetPointer.offset += strlen\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else if ('optional' in def) {\r\n if (data) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, 1, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n byteLength += def.optional.minimumByteLength\r\n maxByteLength += def.optional.minimumByteLength\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n\r\n buffer = def.optional.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n } else {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, 0, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n buffer = def.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n }\r\n\r\n return buffer\r\n }\r\n\r\n private precalculateBufferLengthWithStrings(dataOut: ToJson<T>) {\r\n let len = this.minimumByteLength\r\n\r\n for (const field of this.stringPositions[0]) {\r\n // String field\r\n len += (dataOut[field] as string).length\r\n }\r\n\r\n for (const field of this.stringPositions[1]) {\r\n // Array of strings field\r\n for (const string of dataOut[field] as unknown as string[]) {\r\n len += 2 + string.length\r\n }\r\n }\r\n\r\n for (const field in this.stringPositions[2]) {\r\n // Subpacket that has some string fields\r\n len += this.stringPositions[2][field].precalculateBufferLengthWithStrings(\r\n dataOut[field] as any\r\n )\r\n }\r\n\r\n return len\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | MaybeArray<''>\r\n | { flags: BitFlags }\r\n | { optional: BinaryPacket<Definition> }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : Item extends ''\r\n ? string[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : Item extends ''\r\n ? string[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : T[K] extends { optional: BinaryPacket<infer BPDef extends Definition> }\r\n ? ToJson<BPDef> | undefined\r\n : T[K] extends ''\r\n ? string\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\ntype StringPositions = [\r\n string[],\r\n string[],\r\n {\r\n [field: string]: BinaryPacket<Definition>\r\n }\r\n]\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n\r\n const stringPositions: StringPositions = [[], [], {}]\r\n\r\n for (const [name, type] of entries) {\r\n if (Array.isArray(type)) {\r\n if (type.length === 2) {\r\n // Statically-sized array\r\n const isString = type[0] === ''\r\n\r\n const itemSize =\r\n typeof type[0] === 'object'\r\n ? type[0].minimumByteLength\r\n : isString\r\n ? 2\r\n : BYTE_SIZE[type[0]]\r\n\r\n minimumByteLength += type[1] * itemSize\r\n\r\n if (isString) {\r\n stringPositions[1].push(name)\r\n }\r\n } else {\r\n // Dynamically-sized array\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n\r\n if (type[0] === '') {\r\n stringPositions[1].push(name)\r\n }\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n stringPositions[2][name] = type\r\n } else if (typeof type === 'object') {\r\n // BitFlags & Optionals\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n // Optionals minimum is 1 byte long, because it holds whether the subpacket is present or not\r\n minimumByteLength += 1\r\n } else if (type === '') {\r\n // String\r\n // Adding 2 to serialize the string length\r\n minimumByteLength += 2\r\n stringPositions[0].push(name)\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, stringPositions }\r\n}\r\n\r\n//////////////////////////////////////////////\r\n// The logic here is practically over //\r\n// Here below there are needed constants //\r\n// that map a field-type to a functionality //\r\n//////////////////////////////////////////////\r\n\r\nconst BYTE_SIZE = Array(8) as number[]\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_8] = 1\r\nBYTE_SIZE[Field.INT_8] = 1\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_16] = 2\r\nBYTE_SIZE[Field.INT_16] = 2\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_32] = 4\r\nBYTE_SIZE[Field.INT_32] = 4\r\nBYTE_SIZE[Field.FLOAT_32] = 4\r\n\r\nBYTE_SIZE[Field.FLOAT_64] = 8\r\n\r\nconst GET_FUNCTION = Array(8) as ((view: DataView, offset: number) => number)[]\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_8] = (view, offset) => view.getUint8(offset)\r\nGET_FUNCTION[Field.INT_8] = (view, offset) => view.getInt8(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_16] = (view, offset) => view.getUint16(offset)\r\nGET_FUNCTION[Field.INT_16] = (view, offset) => view.getInt16(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset) => view.getUint32(offset)\r\nGET_FUNCTION[Field.INT_32] = (view, offset) => view.getInt32(offset)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset) => view.getFloat32(offset)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset) => view.getFloat64(offset)\r\n\r\nconst SET_FUNCTION = Array(8) as ((view: DataView, value: number, offset: number) => void)[]\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_8] = (view, value, offset) => view.setUint8(offset, value)\r\nSET_FUNCTION[Field.INT_8] = (view, value, offset) => view.setInt8(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_16] = (view, value, offset) => view.setUint16(offset, value)\r\nSET_FUNCTION[Field.INT_16] = (view, value, offset) => view.setInt16(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_32] = (view, value, offset) => view.setUint32(offset, value)\r\nSET_FUNCTION[Field.INT_32] = (view, value, offset) => view.setInt32(offset, value)\r\nSET_FUNCTION[Field.FLOAT_32] = (view, value, offset) => view.setFloat32(offset, value)\r\n\r\nSET_FUNCTION[Field.FLOAT_64] = (view, value, offset) => view.setFloat64(offset, value)\r\n\r\nconst SET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, value: number, offset: number) => void)[]\r\n\r\nif (hasNodeBuffers) {\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, value, offset) => view.writeUint8(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_8] = (view, value, offset) => view.writeInt8(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, value, offset) =>\r\n view.writeUint16LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_16] = (view, value, offset) => view.writeInt16LE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, value, offset) =>\r\n view.writeUint32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_32] = (view, value, offset) => view.writeInt32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.FLOAT_32] = (view, value, offset) => view.writeFloatLE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.FLOAT_64] = (view, value, offset) => view.writeDoubleLE(value, offset)\r\n}\r\n\r\nconst GET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, offset: number) => number)[]\r\n\r\nif (hasNodeBuffers) {\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, offset) => view.readUint8(offset)\r\n GET_FUNCTION_BUF[Field.INT_8] = (view, offset) => view.readInt8(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, offset) => view.readUint16LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_16] = (view, offset) => view.readInt16LE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, offset) => view.readUint32LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_32] = (view, offset) => view.readInt32LE(offset)\r\n GET_FUNCTION_BUF[Field.FLOAT_32] = (view, offset) => view.readFloatLE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.FLOAT_64] = (view, offset) => view.readDoubleLE(offset)\r\n}\r\n","/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n\r\nconst textEncoder = new TextEncoder()\r\nconst textDecoder = new TextDecoder()\r\n\r\nexport function encodeStringIntoDataView(dataview: DataView, byteOffset: number, string: string) {\r\n const strlen = string.length\r\n const u8Buffer = new Uint8Array(dataview.buffer, dataview.byteOffset + byteOffset, strlen)\r\n\r\n if (strlen <= 64) {\r\n encodeSmallString(u8Buffer, 0, string, strlen)\r\n } else {\r\n textEncoder.encodeInto(string, u8Buffer)\r\n }\r\n}\r\n\r\nexport function encodeStringIntoNodeBuffer(buffer: Buffer, byteOffset: number, string: string) {\r\n const strlen = string.length\r\n\r\n if (strlen <= 64) {\r\n encodeSmallString(buffer, byteOffset, string, strlen)\r\n } else {\r\n buffer.utf8Write(string, byteOffset, strlen)\r\n }\r\n}\r\n\r\nfunction encodeSmallString(buffer: Uint8Array, byteOffset: number, string: string, strlen: number) {\r\n for (let i = 0; i < strlen; ++i) {\r\n buffer[byteOffset + i] = string.charCodeAt(i) & 0xff\r\n }\r\n}\r\n\r\nexport function decodeStringFromNodeBuffer(buffer: Buffer, byteOffset: number, strlen: number) {\r\n return buffer.subarray(byteOffset, byteOffset + strlen).toString('utf8')\r\n}\r\n\r\nexport function decodeStringFromDataView(dataview: DataView, byteOffset: number, strlen: number) {\r\n return textDecoder.decode(new DataView(dataview.buffer, dataview.byteOffset + byteOffset, strlen))\r\n}\r\n\r\ndeclare global {\r\n interface Buffer {\r\n /**\r\n * Node buffer's internals function. \\\r\n * For some reason it is not exposed through TypeScript. \\\r\n * Fastest way to write utf8 strings into buffers.\r\n */\r\n utf8Write(string: string, byteOffset?: number, byteLength?: number): number\r\n }\r\n}\r\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,UAAAC,EAAA,eAAAC,EAAA,kBAAAC,EAAA,oBAAAC,EAA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qB,EAAI,CAAC0C,EAAME,EAAOD,IACtDD,EAAK,cAAcE,EAAOD,CAAM,EAClC3C,EAAiB,CAAY,EAAI,CAAC0C,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EAEzF3C,EAAiB,CAAqB,EAAI,CAAC0C,EAAME,EAAOD,IACtDD,EAAK,cAAcE,EAAOD,CAAM,EAClC3C,EAAiB,CAAY,EAAI,CAAC0C,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EACzF3C,EAAiB,CAAc,EAAI,CAAC0C,EAAME,EAAOD,IAAWD,EAAK,aAAaE,EAAOD,CAAM,EAE3F3C,EAAiB,CAAc,EAAI,CAAC0C,EAAME,EAAOD,IAAWD,EAAK,cAAcE,EAAOD,CAAM,GAG9F,IAAMpD,EAAmB,MAAM,CAAC,EAE5BO,IACFP,EAAiB,CAAoB,EAAI,CAACmD,EAAMC,IAAWD,EAAK,UAAUC,CAAM,EAChFpD,EAAiB,CAAW,EAAI,CAACmD,EAAMC,IAAWD,EAAK,SAASC,CAAM,EAEtEpD,EAAiB,CAAqB,EAAI,CAACmD,EAAMC,IAAWD,EAAK,aAAaC,CAAM,EACpFpD,EAAiB,CAAY,EAAI,CAACmD,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAE1EpD,EAAiB,CAAqB,EAAI,CAACmD,EAAMC,IAAWD,EAAK,aAAaC,CAAM,EACpFpD,EAAiB,CAAY,EAAI,CAACmD,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAC1EpD,EAAiB,CAAc,EAAI,CAACmD,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAE5EpD,EAAiB,CAAc,EAAI,CAACmD,EAAMC,IAAWD,EAAK,aAAaC,CAAM","names":["src_exports","__export","BinaryPacket","Field","FieldArray","FieldBitFlags","FieldFixedArray","FieldOptional","FieldString","__toCommonJS","hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","textEncoder","textDecoder","encodeStringIntoDataView","byteOffset","string","strlen","u8Buffer","encodeSmallString","encodeStringIntoNodeBuffer","i","decodeStringFromNodeBuffer","decodeStringFromDataView","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","FieldString","FieldOptional","packet","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","decodeStringFromNodeBuffer","GET_FUNCTION","decodeStringFromDataView","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","encodeStringIntoNodeBuffer","SET_FUNCTION","growDataView","encodeStringIntoDataView","buf","onVisit","readFunctions","decodeStringFunction","Packet","result","name","def","array","itemType","i","strlen","itemSize","BYTE_SIZE","bit","hasSubPacket","maxByteLength","writeFunctions","growBufferFunction","encodeStringFunction","data","isDynamicArray","neededBytesForElements","object","str","number","len","field","string","fieldName1","fieldName2","entries","minimumByteLength","stringPositions","type","isString","view","offset","value"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var c=typeof Buffer=="function";function D(r,e){let t=new ArrayBuffer(e),i=Math.min(r.byteLength,t.byteLength),n=Math.trunc(i/8);new Float64Array(t,0,n).set(new Float64Array(r.buffer,0,n));let a=n*8;return n=i-a,new Uint8Array(t,a,n).set(new Uint8Array(r.buffer,a,n)),new DataView(t)}function h(r,e){let t=Buffer.allocUnsafe(e);return r.copy(t),t}var E=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(E||{});function L(r){return[r]}function S(r,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[r,e]}function G(r){if(r.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${r.join(", ")}`);return{flags:r}}var p=class r{constructor(e,t){this.packetId=e;this.entries=t?w(t):[],this.minimumByteLength=U(this.entries).minimumByteLength}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new r(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return r.visit(e,m,t)}static visitDataView(e,...t){return r.visit(e,u,t)}static visitArrayBuffer(e,t,i,...n){return r.visit(new DataView(e,t,i),u,n)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,m)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,u)}readArrayBuffer(e,t,i){return this.read(c?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,c?m:u)}writeNodeBuffer(e){let t=Buffer.allocUnsafe(this.minimumByteLength);return this.write(t,e,{offset:0},this.minimumByteLength,this.minimumByteLength,I,h)}writeDataView(e){let t=new DataView(new ArrayBuffer(this.minimumByteLength));return this.write(t,e,{offset:0},this.minimumByteLength,this.minimumByteLength,_,D)}writeArrayBuffer(e){let t=c?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;minimumByteLength;static visit(e,t,i){for(let[n,a]of i)if(n.packetId===t[0](e,0))return a(n.read(e,{offset:0},e.byteLength,t))}read(e,t,i,n){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(n[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let a={};for(let[l,o]of this.entries)if(Array.isArray(o)){let s=o[1]??n[0](e,t.offset++),f=Array(s),d=o[0];if(typeof d=="object")for(let N=0;N<s;++N)f[N]=d.read(e,t,i,n);else{let N=T[d];for(let y=0;y<s;++y)f[y]=n[d](e,t.offset),t.offset+=N}a[l]=f}else if(typeof o=="number")a[l]=n[o](e,t.offset),t.offset+=T[o];else if("flags"in o){let s=n[0](e,t.offset);t.offset+=1,a[l]={};for(let f=0;f<o.flags.length;++f)a[l][o.flags[f]]=!!(s&1<<f)}else a[l]=o.read(e,t,i,n);return a}write(e,t,i,n,a,l,o){l[0](e,this.packetId,i.offset),i.offset+=1;for(let[s,f]of this.entries){let d=t[s];if(Array.isArray(f)){let N=d.length,y=f[1]===void 0;if(y&&(l[0](e,N,i.offset),i.offset+=1),N>0){let B=f[0];if(typeof B=="object"){if(y){let F=N*B.minimumByteLength;n+=F,a+=F,e.byteLength<a&&(e=o(e,a))}for(let F of d)e=B.write(e,F,i,n,a,l,o),n=i.offset,a=e.byteLength}else{let F=T[B];if(y){let g=N*F;n+=g,a+=g,e.byteLength<a&&(e=o(e,a))}for(let g of d)l[B](e,g,i.offset),i.offset+=F}}}else if(typeof f=="number")l[f](e,d,i.offset),i.offset+=T[f];else if("flags"in f){let N=0;for(let y=0;y<f.flags.length;++y)d[f.flags[y]]&&(N|=1<<y);l[0](e,N,i.offset),i.offset+=1}else e=f.write(e,d,i,n,a,l,o),n=i.offset,a=e.byteLength}return e}};function w(r){return Object.entries(r).sort(([e],[t])=>e.localeCompare(t))}function U(r){let e=1;for(let[,t]of r)if(Array.isArray(t))if(t.length===2){let i=typeof t[0]=="object"?t[0].minimumByteLength:T[t[0]];e+=t[1]*i}else e+=1;else t instanceof p?e+=t.minimumByteLength:typeof t=="object"?e+=1:e+=T[t];return{minimumByteLength:e}}var T=Array(8);T[0]=1;T[3]=1;T[1]=2;T[4]=2;T[2]=4;T[5]=4;T[6]=4;T[7]=8;var u=Array(8);u[0]=(r,e)=>r.getUint8(e);u[3]=(r,e)=>r.getInt8(e);u[1]=(r,e)=>r.getUint16(e);u[4]=(r,e)=>r.getInt16(e);u[2]=(r,e)=>r.getUint32(e);u[5]=(r,e)=>r.getInt32(e);u[6]=(r,e)=>r.getFloat32(e);u[7]=(r,e)=>r.getFloat64(e);var _=Array(8);_[0]=(r,e,t)=>r.setUint8(t,e);_[3]=(r,e,t)=>r.setInt8(t,e);_[1]=(r,e,t)=>r.setUint16(t,e);_[4]=(r,e,t)=>r.setInt16(t,e);_[2]=(r,e,t)=>r.setUint32(t,e);_[5]=(r,e,t)=>r.setInt32(t,e);_[6]=(r,e,t)=>r.setFloat32(t,e);_[7]=(r,e,t)=>r.setFloat64(t,e);var I=Array(8);c&&(I[0]=(r,e,t)=>r.writeUint8(e,t),I[3]=(r,e,t)=>r.writeInt8(e,t),I[1]=(r,e,t)=>r.writeUint16LE(e,t),I[4]=(r,e,t)=>r.writeInt16LE(e,t),I[2]=(r,e,t)=>r.writeUint32LE(e,t),I[5]=(r,e,t)=>r.writeInt32LE(e,t),I[6]=(r,e,t)=>r.writeFloatLE(e,t),I[7]=(r,e,t)=>r.writeDoubleLE(e,t));var m=Array(8);c&&(m[0]=(r,e)=>r.readUint8(e),m[3]=(r,e)=>r.readInt8(e),m[1]=(r,e)=>r.readUint16LE(e),m[4]=(r,e)=>r.readInt16LE(e),m[2]=(r,e)=>r.readUint32LE(e),m[5]=(r,e)=>r.readInt32LE(e),m[6]=(r,e)=>r.readFloatLE(e),m[7]=(r,e)=>r.readDoubleLE(e));export{p as BinaryPacket,E as Field,L as FieldArray,G as FieldBitFlags,S as FieldFixedArray};
1
+ var D=typeof Buffer=="function";function w(n,e){let t=new ArrayBuffer(e),i=Math.min(n.byteLength,t.byteLength),r=Math.trunc(i/8);new Float64Array(t,0,r).set(new Float64Array(n.buffer,0,r));let a=r*8;return r=i-a,new Uint8Array(t,a,r).set(new Uint8Array(n.buffer,a,r)),new DataView(t)}function b(n,e){let t=Buffer.allocUnsafe(e);return n.copy(t),t}var G=new TextEncoder,x=new TextDecoder;function A(n,e,t){let i=t.length,r=new Uint8Array(n.buffer,n.byteOffset+e,i);i<=64?L(r,0,t,i):G.encodeInto(t,r)}function S(n,e,t){let i=t.length;i<=64?L(n,e,t,i):n.utf8Write(t,e,i)}function L(n,e,t,i){for(let r=0;r<i;++r)n[e+r]=t.charCodeAt(r)&255}function E(n,e,t){return n.subarray(e,e+t).toString("utf8")}function h(n,e,t){return x.decode(new DataView(n.buffer,n.byteOffset+e,t))}var V=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(V||{});function C(n){return[n]}function j(n,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[n,e]}function K(n){if(n.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${n.join(", ")}`);return{flags:n}}function R(){return""}function M(n){return{optional:n}}var F=class n{constructor(e,t){this.packetId=e;this.entries=t?k(t):[];let i=v(this.entries);this.minimumByteLength=i.minimumByteLength,this.stringPositions=i.stringPositions}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new n(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return n.visit(e,I,E,t)}static visitDataView(e,...t){return n.visit(e,g,h,t)}static visitArrayBuffer(e,t,i,...r){return n.visit(new DataView(e,t,i),g,h,r)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,I,E)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,g,h)}readArrayBuffer(e,t,i){return this.read(D?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,D?I:g,D?E:h)}writeNodeBuffer(e){let t=this.precalculateBufferLengthWithStrings(e),i=Buffer.allocUnsafe(t);return this.write(i,e,{offset:0},t,t,c,b,S)}writeDataView(e){let t=this.precalculateBufferLengthWithStrings(e),i=new DataView(new ArrayBuffer(t));return this.write(i,e,{offset:0},t,t,_,w,A)}writeArrayBuffer(e){let t=D?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;stringPositions;minimumByteLength;static visit(e,t,i,r){for(let[a,o]of r)if(a.packetId===t[0](e,0))return o(a.read(e,{offset:0},e.byteLength,t,i))}read(e,t,i,r,a){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(r[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let o={};for(let[u,s]of this.entries)if(Array.isArray(s)){let d=s[1]??r[0](e,t.offset++),f=Array(d),T=s[0];if(typeof T=="object")for(let l=0;l<d;++l)f[l]=T.read(e,t,i,r,a);else if(T==="")for(let l=0;l<d;++l){let N=r[1](e,t.offset);t.offset+=2,f[l]=a(e,t.offset,N),t.offset+=N}else{let l=y[T];for(let N=0;N<d;++N)f[N]=r[T](e,t.offset),t.offset+=l}o[u]=f}else if(typeof s=="number")o[u]=r[s](e,t.offset),t.offset+=y[s];else if(s===""){let d=r[1](e,t.offset);t.offset+=2,o[u]=a(e,t.offset,d),t.offset+=d}else if("flags"in s){let d=r[0](e,t.offset);t.offset+=1,o[u]={};for(let f=0;f<s.flags.length;++f)o[u][s.flags[f]]=!!(d&1<<f)}else if("optional"in s){let d=r[0](e,t.offset)!==0;t.offset+=1,d&&(o[u]=s.optional.read(e,t,i,r,a))}else o[u]=s.read(e,t,i,r,a);return o}write(e,t,i,r,a,o,u,s){o[0](e,this.packetId,i.offset),i.offset+=1;for(let[d,f]of this.entries){let T=t[d];if(Array.isArray(f)){let l=T.length,N=f[1]===void 0;if(N&&(o[0](e,l,i.offset),i.offset+=1),l>0){let B=f[0];if(typeof B=="object"){if(N){let m=l*B.minimumByteLength;r+=m,a+=m,e.byteLength<a&&(e=u(e,a))}for(let m of T)e=B.write(e,m,i,r,a,o,u,s),r=i.offset,a=e.byteLength}else if(B==="")for(let m=0;m<l;++m){let p=T[m],U=p.length;o[1](e,U,i.offset),i.offset+=2,s(e,i.offset,p),i.offset+=U}else{let m=y[B];if(N){let p=l*m;r+=p,a+=p,e.byteLength<a&&(e=u(e,a))}for(let p of T)o[B](e,p,i.offset),i.offset+=m}}}else if(typeof f=="number")o[f](e,T,i.offset),i.offset+=y[f];else if(f===""){let l=T.length;o[1](e,l,i.offset),i.offset+=2,s(e,i.offset,T),i.offset+=l}else if("flags"in f){let l=0;for(let N=0;N<f.flags.length;++N)T[f.flags[N]]&&(l|=1<<N);o[0](e,l,i.offset),i.offset+=1}else"optional"in f?T?(o[0](e,1,i.offset),i.offset+=1,r+=f.optional.minimumByteLength,a+=f.optional.minimumByteLength,e.byteLength<a&&(e=u(e,a)),e=f.optional.write(e,T,i,r,a,o,u,s),r=i.offset,a=e.byteLength):(o[0](e,0,i.offset),i.offset+=1):(e=f.write(e,T,i,r,a,o,u,s),r=i.offset,a=e.byteLength)}return e}precalculateBufferLengthWithStrings(e){let t=this.minimumByteLength;for(let i of this.stringPositions[0])t+=e[i].length;for(let i of this.stringPositions[1])for(let r of e[i])t+=2+r.length;for(let i in this.stringPositions[2])t+=this.stringPositions[2][i].precalculateBufferLengthWithStrings(e[i]);return t}};function k(n){return Object.entries(n).sort(([e],[t])=>e.localeCompare(t))}function v(n){let e=1,t=[[],[],{}];for(let[i,r]of n)if(Array.isArray(r))if(r.length===2){let a=r[0]==="",o=typeof r[0]=="object"?r[0].minimumByteLength:a?2:y[r[0]];e+=r[1]*o,a&&t[1].push(i)}else e+=1,r[0]===""&&t[1].push(i);else r instanceof F?(e+=r.minimumByteLength,t[2][i]=r):typeof r=="object"?e+=1:r===""?(e+=2,t[0].push(i)):e+=y[r];return{minimumByteLength:e,stringPositions:t}}var y=Array(8);y[0]=1;y[3]=1;y[1]=2;y[4]=2;y[2]=4;y[5]=4;y[6]=4;y[7]=8;var g=Array(8);g[0]=(n,e)=>n.getUint8(e);g[3]=(n,e)=>n.getInt8(e);g[1]=(n,e)=>n.getUint16(e);g[4]=(n,e)=>n.getInt16(e);g[2]=(n,e)=>n.getUint32(e);g[5]=(n,e)=>n.getInt32(e);g[6]=(n,e)=>n.getFloat32(e);g[7]=(n,e)=>n.getFloat64(e);var _=Array(8);_[0]=(n,e,t)=>n.setUint8(t,e);_[3]=(n,e,t)=>n.setInt8(t,e);_[1]=(n,e,t)=>n.setUint16(t,e);_[4]=(n,e,t)=>n.setInt16(t,e);_[2]=(n,e,t)=>n.setUint32(t,e);_[5]=(n,e,t)=>n.setInt32(t,e);_[6]=(n,e,t)=>n.setFloat32(t,e);_[7]=(n,e,t)=>n.setFloat64(t,e);var c=Array(8);D&&(c[0]=(n,e,t)=>n.writeUint8(e,t),c[3]=(n,e,t)=>n.writeInt8(e,t),c[1]=(n,e,t)=>n.writeUint16LE(e,t),c[4]=(n,e,t)=>n.writeInt16LE(e,t),c[2]=(n,e,t)=>n.writeUint32LE(e,t),c[5]=(n,e,t)=>n.writeInt32LE(e,t),c[6]=(n,e,t)=>n.writeFloatLE(e,t),c[7]=(n,e,t)=>n.writeDoubleLE(e,t));var I=Array(8);D&&(I[0]=(n,e)=>n.readUint8(e),I[3]=(n,e)=>n.readInt8(e),I[1]=(n,e)=>n.readUint16LE(e),I[4]=(n,e)=>n.readInt16LE(e),I[2]=(n,e)=>n.readUint32LE(e),I[5]=(n,e)=>n.readInt32LE(e),I[6]=(n,e)=>n.readFloatLE(e),I[7]=(n,e)=>n.readDoubleLE(e));export{F as BinaryPacket,V as Field,C as FieldArray,K as FieldBitFlags,j as FieldFixedArray,M as FieldOptional,R as FieldString};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/buffers.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n","import { growDataView, growNodeBuffer, hasNodeBuffers, type TrueArrayBuffer } from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION_BUF)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : new DataView(dataIn, byteOffset, byteLength),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const buffer = Buffer.allocUnsafe(this.minimumByteLength)\r\n\r\n return this.write(\r\n buffer,\r\n dataOut,\r\n { offset: 0 },\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n SET_FUNCTION_BUF,\r\n growNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a DataView. \\\r\n */\r\n writeDataView(dataOut: ToJson<T>) {\r\n const dataview = new DataView(new ArrayBuffer(this.minimumByteLength))\r\n\r\n return this.write(\r\n dataview,\r\n dataOut,\r\n { offset: 0 },\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n SET_FUNCTION,\r\n growDataView\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into an ArrayBuffer. \\\r\n * This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \\\r\n *\r\n * This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \\\r\n * Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \\\r\n *\r\n * Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \\\r\n * For more information read the `readArrayBuffer` documentation.\r\n */\r\n writeArrayBuffer(dataOut: ToJson<T>) {\r\n const buf = hasNodeBuffers ? this.writeNodeBuffer(dataOut) : this.writeDataView(dataOut)\r\n return { buffer: buf.buffer, byteLength: buf.byteLength, byteOffset: buf.byteOffset }\r\n }\r\n\r\n /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly minimumByteLength: number\r\n\r\n private constructor(\r\n private readonly packetId: number,\r\n definition?: T\r\n ) {\r\n this.entries = definition ? sortEntries(definition) : []\r\n this.minimumByteLength = inspectEntries(this.entries).minimumByteLength\r\n }\r\n\r\n private static visit(\r\n dataIn: Buffer | DataView,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions))\r\n }\r\n }\r\n }\r\n\r\n private read(\r\n dataIn: DataView | Buffer,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n maxByteLength: number,\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF,\r\n growBufferFunction: (buffer: Buf, newByteLength: number) => Buf\r\n ): Buf {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, this.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n for (const [name, def] of this.entries) {\r\n const data = dataOut[name]\r\n\r\n if (Array.isArray(def)) {\r\n // Could be both an array of just numbers or \"subpackets\"\r\n\r\n const length = (data as any[]).length\r\n\r\n // Check if it is a dynamically-sized array, if it is, the length of the array must be serialized in the buffer before its elements\r\n // Explicitly check for undefined and not falsy values because it could be a statically-sized array of 0 elements.\r\n const isDynamicArray = def[1] === undefined\r\n\r\n if (isDynamicArray) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n\r\n if (length > 0) {\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemType.minimumByteLength\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n for (const object of data as unknown as ToJson<Definition>[]) {\r\n buffer = itemType.write(\r\n buffer,\r\n object,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemSize\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (const number of data as number[]) {\r\n writeFunctions[itemType](buffer as any, number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n buffer = def.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n\r\n for (const [, type] of entries) {\r\n if (Array.isArray(type)) {\r\n if (type.length === 2) {\r\n // Statically-sized array\r\n const itemSize =\r\n typeof type[0] === 'object' ? type[0].minimumByteLength : BYTE_SIZE[type[0]]\r\n\r\n minimumByteLength += type[1] * itemSize\r\n } else {\r\n // Dynamically-sized array\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n } else if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength }\r\n}\r\n\r\n//////////////////////////////////////////////\r\n// The logic here is practically over //\r\n// Here below there are needed constants //\r\n// that map a field-type to a functionality //\r\n//////////////////////////////////////////////\r\n\r\nconst BYTE_SIZE = Array(8) as number[]\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_8] = 1\r\nBYTE_SIZE[Field.INT_8] = 1\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_16] = 2\r\nBYTE_SIZE[Field.INT_16] = 2\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_32] = 4\r\nBYTE_SIZE[Field.INT_32] = 4\r\nBYTE_SIZE[Field.FLOAT_32] = 4\r\n\r\nBYTE_SIZE[Field.FLOAT_64] = 8\r\n\r\nconst GET_FUNCTION = Array(8) as ((view: DataView, offset: number) => number)[]\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_8] = (view, offset) => view.getUint8(offset)\r\nGET_FUNCTION[Field.INT_8] = (view, offset) => view.getInt8(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_16] = (view, offset) => view.getUint16(offset)\r\nGET_FUNCTION[Field.INT_16] = (view, offset) => view.getInt16(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset) => view.getUint32(offset)\r\nGET_FUNCTION[Field.INT_32] = (view, offset) => view.getInt32(offset)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset) => view.getFloat32(offset)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset) => view.getFloat64(offset)\r\n\r\nconst SET_FUNCTION = Array(8) as ((view: DataView, value: number, offset: number) => void)[]\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_8] = (view, value, offset) => view.setUint8(offset, value)\r\nSET_FUNCTION[Field.INT_8] = (view, value, offset) => view.setInt8(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_16] = (view, value, offset) => view.setUint16(offset, value)\r\nSET_FUNCTION[Field.INT_16] = (view, value, offset) => view.setInt16(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_32] = (view, value, offset) => view.setUint32(offset, value)\r\nSET_FUNCTION[Field.INT_32] = (view, value, offset) => view.setInt32(offset, value)\r\nSET_FUNCTION[Field.FLOAT_32] = (view, value, offset) => view.setFloat32(offset, value)\r\n\r\nSET_FUNCTION[Field.FLOAT_64] = (view, value, offset) => view.setFloat64(offset, value)\r\n\r\nconst SET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, value: number, offset: number) => void)[]\r\n\r\nif (hasNodeBuffers) {\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, value, offset) => view.writeUint8(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_8] = (view, value, offset) => view.writeInt8(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, value, offset) =>\r\n view.writeUint16LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_16] = (view, value, offset) => view.writeInt16LE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, value, offset) =>\r\n view.writeUint32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_32] = (view, value, offset) => view.writeInt32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.FLOAT_32] = (view, value, offset) => view.writeFloatLE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.FLOAT_64] = (view, value, offset) => view.writeDoubleLE(value, offset)\r\n}\r\n\r\nconst GET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, offset: number) => number)[]\r\n\r\nif (hasNodeBuffers) {\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, offset) => view.readUint8(offset)\r\n GET_FUNCTION_BUF[Field.INT_8] = (view, offset) => view.readInt8(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, offset) => view.readUint16LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_16] = (view, offset) => view.readInt16LE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, offset) => view.readUint32LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_32] = (view, offset) => view.readInt32LE(offset)\r\n GET_FUNCTION_BUF[Field.FLOAT_32] = (view, offset) => view.readFloatLE(offset)\r\n\r\n GET_FUNCTION_BUF[Field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AK,YAAYC,CAAM,EAE5EtC,EAAiB,CAAc,EAAI,CAACqC,EAAMC,IAAWD,EAAK,aAAaC,CAAM","names":["hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","GET_FUNCTION","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","onVisit","readFunctions","Packet","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","maxByteLength","writeFunctions","growBufferFunction","data","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","type","view","offset","value"]}
1
+ {"version":3,"sources":["../src/buffers.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n\r\nconst textEncoder = new TextEncoder()\r\nconst textDecoder = new TextDecoder()\r\n\r\nexport function encodeStringIntoDataView(dataview: DataView, byteOffset: number, string: string) {\r\n const strlen = string.length\r\n const u8Buffer = new Uint8Array(dataview.buffer, dataview.byteOffset + byteOffset, strlen)\r\n\r\n if (strlen <= 64) {\r\n encodeSmallString(u8Buffer, 0, string, strlen)\r\n } else {\r\n textEncoder.encodeInto(string, u8Buffer)\r\n }\r\n}\r\n\r\nexport function encodeStringIntoNodeBuffer(buffer: Buffer, byteOffset: number, string: string) {\r\n const strlen = string.length\r\n\r\n if (strlen <= 64) {\r\n encodeSmallString(buffer, byteOffset, string, strlen)\r\n } else {\r\n buffer.utf8Write(string, byteOffset, strlen)\r\n }\r\n}\r\n\r\nfunction encodeSmallString(buffer: Uint8Array, byteOffset: number, string: string, strlen: number) {\r\n for (let i = 0; i < strlen; ++i) {\r\n buffer[byteOffset + i] = string.charCodeAt(i) & 0xff\r\n }\r\n}\r\n\r\nexport function decodeStringFromNodeBuffer(buffer: Buffer, byteOffset: number, strlen: number) {\r\n return buffer.subarray(byteOffset, byteOffset + strlen).toString('utf8')\r\n}\r\n\r\nexport function decodeStringFromDataView(dataview: DataView, byteOffset: number, strlen: number) {\r\n return textDecoder.decode(new DataView(dataview.buffer, dataview.byteOffset + byteOffset, strlen))\r\n}\r\n\r\ndeclare global {\r\n interface Buffer {\r\n /**\r\n * Node buffer's internals function. \\\r\n * For some reason it is not exposed through TypeScript. \\\r\n * Fastest way to write utf8 strings into buffers.\r\n */\r\n utf8Write(string: string, byteOffset?: number, byteLength?: number): number\r\n }\r\n}\r\n","import {\r\n decodeStringFromDataView,\r\n decodeStringFromNodeBuffer,\r\n encodeStringIntoDataView,\r\n encodeStringIntoNodeBuffer,\r\n growDataView,\r\n growNodeBuffer,\r\n hasNodeBuffers,\r\n type TrueArrayBuffer\r\n} from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition> | ''>(\r\n item: T\r\n): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<\r\n T extends Field | BinaryPacket<Definition> | '',\r\n Length extends number\r\n>(item: T, length: Length): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Defines a string field. \\\r\n * Strings cannot be more than 65536 characters long.\r\n *\r\n * NOTE: Only strings containing just ASCII and/or single-octet UTF-8 characters are supported.\r\n */\r\nexport function FieldString() {\r\n return '' as const\r\n}\r\n\r\n/**\r\n * Defines an optional BinaryPacket \"subpacket\" field. \\\r\n * When writing and reading packets it'll be possible to provide and receive `undefined` instead of a valid object.\r\n */\r\nexport function FieldOptional<T extends BinaryPacket<Definition>>(packet: T) {\r\n return { optional: packet }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, decodeStringFromNodeBuffer, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, decodeStringFromDataView, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n decodeStringFromDataView,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n GET_FUNCTION_BUF,\r\n decodeStringFromNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION, decodeStringFromDataView)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : (new DataView(dataIn, byteOffset, byteLength) as any),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION,\r\n hasNodeBuffers ? decodeStringFromNodeBuffer : (decodeStringFromDataView as any)\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const byteLength = this.precalculateBufferLengthWithStrings(dataOut)\r\n const buffer = Buffer.allocUnsafe(byteLength)\r\n\r\n return this.write(\r\n buffer,\r\n dataOut,\r\n { offset: 0 },\r\n byteLength,\r\n byteLength,\r\n SET_FUNCTION_BUF,\r\n growNodeBuffer,\r\n encodeStringIntoNodeBuffer\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a DataView. \\\r\n */\r\n writeDataView(dataOut: ToJson<T>) {\r\n const byteLength = this.precalculateBufferLengthWithStrings(dataOut)\r\n const dataview = new DataView(new ArrayBuffer(byteLength))\r\n\r\n return this.write(\r\n dataview,\r\n dataOut,\r\n { offset: 0 },\r\n byteLength,\r\n byteLength,\r\n SET_FUNCTION,\r\n growDataView,\r\n encodeStringIntoDataView\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into an ArrayBuffer. \\\r\n * This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \\\r\n *\r\n * This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \\\r\n * Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \\\r\n *\r\n * Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \\\r\n * For more information read the `readArrayBuffer` documentation.\r\n */\r\n writeArrayBuffer(dataOut: ToJson<T>) {\r\n const buf = hasNodeBuffers ? this.writeNodeBuffer(dataOut) : this.writeDataView(dataOut)\r\n return { buffer: buf.buffer, byteLength: buf.byteLength, byteOffset: buf.byteOffset }\r\n }\r\n\r\n /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly stringPositions: StringPositions\r\n readonly minimumByteLength: number\r\n\r\n private constructor(\r\n private readonly packetId: number,\r\n definition?: T\r\n ) {\r\n this.entries = definition ? sortEntries(definition) : []\r\n const inspection = inspectEntries(this.entries)\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.stringPositions = inspection.stringPositions\r\n }\r\n\r\n private static visit<Buf extends DataView | Buffer>(\r\n dataIn: Buf,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n decodeStringFunction: (dataIn: Buf, byteOffset: number, strlen: number) => string,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(\r\n Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions, decodeStringFunction)\r\n )\r\n }\r\n }\r\n }\r\n\r\n private read<Buf extends DataView | Buffer>(\r\n dataIn: Buf,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n decodeStringFunction: (dataIn: Buf, byteOffset: number, strlen: number) => string\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n } else if (itemType === '') {\r\n // Array of strings\r\n for (let i = 0; i < length; ++i) {\r\n const strlen = readFunctions[Field.UNSIGNED_INT_16](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n array[i] = decodeStringFunction(dataIn, offsetPointer.offset, strlen)\r\n offsetPointer.offset += strlen\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if (def === '') {\r\n const strlen = readFunctions[Field.UNSIGNED_INT_16](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = decodeStringFunction(dataIn, offsetPointer.offset, strlen)\r\n offsetPointer.offset += strlen\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else if ('optional' in def) {\r\n // Single optional \"subpacket\"\r\n const hasSubPacket =\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== 0\r\n\r\n offsetPointer.offset += 1\r\n\r\n if (hasSubPacket) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.optional.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(\r\n dataIn,\r\n offsetPointer,\r\n byteLength,\r\n readFunctions,\r\n decodeStringFunction\r\n )\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n maxByteLength: number,\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF,\r\n growBufferFunction: (buffer: Buf, newByteLength: number) => Buf,\r\n encodeStringFunction: (buffer: Buf, byteOffset: number, string: string) => void\r\n ): Buf {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, this.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n for (const [name, def] of this.entries) {\r\n const data = dataOut[name]\r\n\r\n if (Array.isArray(def)) {\r\n // Could be both an array of just numbers or \"subpackets\"\r\n\r\n const length = (data as any[]).length\r\n\r\n // Check if it is a dynamically-sized array, if it is, the length of the array must be serialized in the buffer before its elements\r\n // Explicitly check for undefined and not falsy values because it could be a statically-sized array of 0 elements.\r\n const isDynamicArray = def[1] === undefined\r\n\r\n if (isDynamicArray) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n\r\n if (length > 0) {\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemType.minimumByteLength\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n for (const object of data as unknown as ToJson<Definition>[]) {\r\n // Array of \"subpackets\"\r\n buffer = itemType.write(\r\n buffer,\r\n object,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n } else if (itemType === '') {\r\n // Array of strings\r\n for (let i = 0; i < length; ++i) {\r\n const str = (data as unknown as string[])[i]\r\n const strlen = str.length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_16](buffer as any, strlen, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n encodeStringFunction(buffer, offsetPointer.offset, str)\r\n offsetPointer.offset += strlen\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n if (isDynamicArray) {\r\n const neededBytesForElements = length * itemSize\r\n\r\n byteLength += neededBytesForElements\r\n maxByteLength += neededBytesForElements\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n }\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (const number of data as number[]) {\r\n writeFunctions[itemType](buffer as any, number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if (def === '') {\r\n // String\r\n const strlen = (data as string).length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_16](buffer as any, strlen, offsetPointer.offset)\r\n offsetPointer.offset += 2\r\n\r\n encodeStringFunction(buffer, offsetPointer.offset, data as string)\r\n offsetPointer.offset += strlen\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else if ('optional' in def) {\r\n if (data) {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, 1, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n byteLength += def.optional.minimumByteLength\r\n maxByteLength += def.optional.minimumByteLength\r\n\r\n if (buffer.byteLength < maxByteLength) {\r\n buffer = growBufferFunction(buffer, maxByteLength)\r\n }\r\n\r\n buffer = def.optional.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n } else {\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, 0, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n buffer = def.write(\r\n buffer,\r\n data as ToJson<Definition>,\r\n offsetPointer,\r\n byteLength,\r\n maxByteLength,\r\n writeFunctions,\r\n growBufferFunction,\r\n encodeStringFunction\r\n )\r\n\r\n byteLength = offsetPointer.offset\r\n maxByteLength = buffer.byteLength\r\n }\r\n }\r\n\r\n return buffer\r\n }\r\n\r\n private precalculateBufferLengthWithStrings(dataOut: ToJson<T>) {\r\n let len = this.minimumByteLength\r\n\r\n for (const field of this.stringPositions[0]) {\r\n // String field\r\n len += (dataOut[field] as string).length\r\n }\r\n\r\n for (const field of this.stringPositions[1]) {\r\n // Array of strings field\r\n for (const string of dataOut[field] as unknown as string[]) {\r\n len += 2 + string.length\r\n }\r\n }\r\n\r\n for (const field in this.stringPositions[2]) {\r\n // Subpacket that has some string fields\r\n len += this.stringPositions[2][field].precalculateBufferLengthWithStrings(\r\n dataOut[field] as any\r\n )\r\n }\r\n\r\n return len\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | MaybeArray<''>\r\n | { flags: BitFlags }\r\n | { optional: BinaryPacket<Definition> }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : Item extends ''\r\n ? string[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : Item extends ''\r\n ? string[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : T[K] extends { optional: BinaryPacket<infer BPDef extends Definition> }\r\n ? ToJson<BPDef> | undefined\r\n : T[K] extends ''\r\n ? string\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\ntype StringPositions = [\r\n string[],\r\n string[],\r\n {\r\n [field: string]: BinaryPacket<Definition>\r\n }\r\n]\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n\r\n const stringPositions: StringPositions = [[], [], {}]\r\n\r\n for (const [name, type] of entries) {\r\n if (Array.isArray(type)) {\r\n if (type.length === 2) {\r\n // Statically-sized array\r\n const isString = type[0] === ''\r\n\r\n const itemSize =\r\n typeof type[0] === 'object'\r\n ? type[0].minimumByteLength\r\n : isString\r\n ? 2\r\n : BYTE_SIZE[type[0]]\r\n\r\n minimumByteLength += type[1] * itemSize\r\n\r\n if (isString) {\r\n stringPositions[1].push(name)\r\n }\r\n } else {\r\n // Dynamically-sized array\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n\r\n if (type[0] === '') {\r\n stringPositions[1].push(name)\r\n }\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n stringPositions[2][name] = type\r\n } else if (typeof type === 'object') {\r\n // BitFlags & Optionals\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n // Optionals minimum is 1 byte long, because it holds whether the subpacket is present or not\r\n minimumByteLength += 1\r\n } else if (type === '') {\r\n // String\r\n // Adding 2 to serialize the string length\r\n minimumByteLength += 2\r\n stringPositions[0].push(name)\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, stringPositions }\r\n}\r\n\r\n//////////////////////////////////////////////\r\n// The logic here is practically over //\r\n// Here below there are needed constants //\r\n// that map a field-type to a functionality //\r\n//////////////////////////////////////////////\r\n\r\nconst BYTE_SIZE = Array(8) as number[]\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_8] = 1\r\nBYTE_SIZE[Field.INT_8] = 1\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_16] = 2\r\nBYTE_SIZE[Field.INT_16] = 2\r\n\r\nBYTE_SIZE[Field.UNSIGNED_INT_32] = 4\r\nBYTE_SIZE[Field.INT_32] = 4\r\nBYTE_SIZE[Field.FLOAT_32] = 4\r\n\r\nBYTE_SIZE[Field.FLOAT_64] = 8\r\n\r\nconst GET_FUNCTION = Array(8) as ((view: DataView, offset: number) => number)[]\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_8] = (view, offset) => view.getUint8(offset)\r\nGET_FUNCTION[Field.INT_8] = (view, offset) => view.getInt8(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_16] = (view, offset) => view.getUint16(offset)\r\nGET_FUNCTION[Field.INT_16] = (view, offset) => view.getInt16(offset)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset) => view.getUint32(offset)\r\nGET_FUNCTION[Field.INT_32] = (view, offset) => view.getInt32(offset)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset) => view.getFloat32(offset)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset) => view.getFloat64(offset)\r\n\r\nconst SET_FUNCTION = Array(8) as ((view: DataView, value: number, offset: number) => void)[]\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_8] = (view, value, offset) => view.setUint8(offset, value)\r\nSET_FUNCTION[Field.INT_8] = (view, value, offset) => view.setInt8(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_16] = (view, value, offset) => view.setUint16(offset, value)\r\nSET_FUNCTION[Field.INT_16] = (view, value, offset) => view.setInt16(offset, value)\r\n\r\nSET_FUNCTION[Field.UNSIGNED_INT_32] = (view, value, offset) => view.setUint32(offset, value)\r\nSET_FUNCTION[Field.INT_32] = (view, value, offset) => view.setInt32(offset, value)\r\nSET_FUNCTION[Field.FLOAT_32] = (view, value, offset) => view.setFloat32(offset, value)\r\n\r\nSET_FUNCTION[Field.FLOAT_64] = (view, value, offset) => view.setFloat64(offset, value)\r\n\r\nconst SET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, value: number, offset: number) => void)[]\r\n\r\nif (hasNodeBuffers) {\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, value, offset) => view.writeUint8(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_8] = (view, value, offset) => view.writeInt8(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, value, offset) =>\r\n view.writeUint16LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_16] = (view, value, offset) => view.writeInt16LE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, value, offset) =>\r\n view.writeUint32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.INT_32] = (view, value, offset) => view.writeInt32LE(value, offset)\r\n SET_FUNCTION_BUF[Field.FLOAT_32] = (view, value, offset) => view.writeFloatLE(value, offset)\r\n\r\n SET_FUNCTION_BUF[Field.FLOAT_64] = (view, value, offset) => view.writeDoubleLE(value, offset)\r\n}\r\n\r\nconst GET_FUNCTION_BUF = Array(8) as ((nodeBuffer: Buffer, offset: number) => number)[]\r\n\r\nif (hasNodeBuffers) {\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_8] = (view, offset) => view.readUint8(offset)\r\n GET_FUNCTION_BUF[Field.INT_8] = (view, offset) => view.readInt8(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_16] = (view, offset) => view.readUint16LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_16] = (view, offset) => view.readInt16LE(offset)\r\n\r\n GET_FUNCTION_BUF[Field.UNSIGNED_INT_32] = (view, offset) => view.readUint32LE(offset)\r\n GET_FUNCTION_BUF[Field.INT_32] = (view, offset) => view.readInt32LE(offset)\r\n GET_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eBuffer","buffer","newBuffer","textEncoder","textDecoder","encodeStringIntoDataView","byteOffset","string","strlen","u8Buffer","encodeSmallString","encodeStringIntoNodeBuffer","i","decodeStringFromNodeBuffer","decodeStringFromDataView","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","FieldString","FieldOptional","packet","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","decodeStringFromNodeBuffer","GET_FUNCTION","decodeStringFromDataView","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","encodeStringIntoNodeBuffer","SET_FUNCTION","growDataView","encodeStringIntoDataView","buf","onVisit","readFunctions","decodeStringFunction","Packet","result","name","def","array","itemType","i","strlen","itemSize","BYTE_SIZE","bit","hasSubPacket","maxByteLength","writeFunctions","growBufferFunction","encodeStringFunction","data","isDynamicArray","neededBytesForElements","object","str","number","len","field","string","fieldName1","fieldName2","entries","minimumByteLength","stringPositions","type","isString","view","offset","value"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "binary-packet",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "Lightweight and hyper-fast, zero-dependencies, TypeScript-first, schema-based binary packets serialization and deserialization library",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",