binary-packet 1.0.3 → 1.0.5

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
@@ -31,9 +31,11 @@ Currently, these kinds of `fields` are supported:
31
31
  | `Field.FLOAT_32` | 32 bits IEEE754 floating-point | | 4 |
32
32
  | `Field.FLOAT_64` | 64 bits IEEE754 floating-point | | 8 |
33
33
  | `BinaryPacket` | BinaryPacket "subpacket" | BinaryPacket | size(BinaryPacket) |
34
- | `FieldArray` | Array of one of the types above | Up to 256 elements | 1 + length \* size(Field) |
34
+ | `FieldArray` | Dynamically-sized array of one of the types above | Up to 256 elements | 1 + length \* size(Element) |
35
+ | `FieldFixedArray` | Statically-sized array of one of the types above | Any pre-defined numbers of elements | length \* size(Element) |
35
36
 
36
- As you can see from the table above, both arrays and nested objects ("subpackets") are supported.
37
+ As you can see from the table above, both arrays and nested objects ("subpackets") are supported. \
38
+ Note that `FieldFixedArray`s are much more memory efficient and performant than `FieldArray`s, but require a pre-defined length.
37
39
 
38
40
  ## Usage Examples
39
41
 
@@ -57,7 +59,7 @@ const CellPacket = BinaryPacket.define(0, Cell)
57
59
  const Board = {
58
60
  numPlayers: Field.UNSIGNED_INT_8,
59
61
  otherStuff: Field.INT_32,
60
- cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
62
+ cells: FieldArray(CellPacket)
61
63
  }
62
64
 
63
65
  // When done with the board definition we can create its BinaryPacket writer/reader.
@@ -108,14 +110,14 @@ So, take these "performance" comparisons with a grain of salt; or, even better,
108
110
 
109
111
  This library has been benchmarked against the following alternatives:
110
112
 
111
- - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular and very fast and battle-tested serialization library. It currently offers **many** more features than binary-packet, but it appears to be 2x-4x slower in writes and 3x-10x slower in reads.
112
- - [restructure](https://www.npmjs.com/package/restructure) - A very popular schema-based serialization 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.
113
+ - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular, fast and battle-tested library. Currently offers **many** 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.
114
+ - [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.
113
115
 
114
116
  The benchmarks are executed on three different kinds of packets:
115
117
 
116
118
  - EmptyPacket: basically an empty javascript object.
117
- - SimplePacket: objects with primitive-only fields.
118
- - ComplexPacket: objects with primitives, arrays and other nested objects/arrays.
119
+ - SimplePacket: objects with just primitive fields and statically-sized arrays.
120
+ - ComplexPacket: objects with primitives, statically-sized arrays, dynamically-sized arrays and other nested objects/arrays.
119
121
 
120
122
  You can see and run the benchmarks yourself if you clone the repository and launch `npm run benchmark`.
121
123
 
package/dist/index.d.mts CHANGED
@@ -39,10 +39,22 @@ declare const enum Field {
39
39
  FLOAT_64 = 7
40
40
  }
41
41
  /**
42
- * Defines an array of a certain type. \
43
- * As of now, only arrays with at most 256 elements are supported.
42
+ * Defines a dynamically-sized array with elements of a certain type. \
43
+ * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \
44
+ * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.
45
+ *
46
+ * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \
47
+ * NOTE: As of now, dynamic arrays can have at most 256 elements.
48
+ */
49
+ declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T];
50
+ /**
51
+ * Defines a statically-sized array with elements of a certain type. \
52
+ * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \
53
+ * Fixed arrays much more memory efficient and performant than non-fixed ones.
54
+ *
55
+ * NOTE: If an array will not always have the same length, use the `FieldArray` type.
44
56
  */
45
- declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): T[];
57
+ declare function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(item: T, length: Length): [itemType: T, length: Length];
46
58
  declare class BinaryPacket<T extends Definition> {
47
59
  private readonly packetId;
48
60
  /**
@@ -139,10 +151,13 @@ declare class BinaryPacket<T extends Definition> {
139
151
  private constructor();
140
152
  private read;
141
153
  private write;
154
+ /**
155
+ * Fast write does not support writing dynamically-sized arrays.
156
+ */
142
157
  private fastWrite;
143
158
  /**
144
159
  * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
145
- * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
160
+ * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.
146
161
  */
147
162
  private slowWrite;
148
163
  }
@@ -167,7 +182,7 @@ declare class BinaryPacket<T extends Definition> {
167
182
  * // You can also specify arrays of both "primitive" fields and other BinaryPackets.
168
183
  * const Board = {
169
184
  * numPlayers: Field.UNSIGNED_INT_8,
170
- * cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
185
+ * cells: FieldArray(CellPacket)
171
186
  * }
172
187
  *
173
188
  * // When done with the board definition we can create its BinaryPacket writer/reader.
@@ -190,13 +205,18 @@ declare class BinaryPacket<T extends Definition> {
190
205
  * // ...
191
206
  */
192
207
  type Definition = {
193
- [fieldName: string]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[];
208
+ [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>>;
194
209
  };
210
+ type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
195
211
  /**
196
212
  * 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. \
197
213
  */
198
214
  type ToJson<T extends Definition> = {
199
- [K in keyof T]: T[K] extends ReadonlyArray<infer Item> ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
215
+ [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>[] & {
216
+ length: Length;
217
+ } : number[] & {
218
+ length: Length;
219
+ } : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
200
220
  };
201
221
 
202
- export { BinaryPacket, type Definition, Field, FieldArray };
222
+ export { BinaryPacket, type Definition, Field, FieldArray, FieldFixedArray };
package/dist/index.d.ts CHANGED
@@ -39,10 +39,22 @@ declare const enum Field {
39
39
  FLOAT_64 = 7
40
40
  }
41
41
  /**
42
- * Defines an array of a certain type. \
43
- * As of now, only arrays with at most 256 elements are supported.
42
+ * Defines a dynamically-sized array with elements of a certain type. \
43
+ * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \
44
+ * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.
45
+ *
46
+ * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \
47
+ * NOTE: As of now, dynamic arrays can have at most 256 elements.
48
+ */
49
+ declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T];
50
+ /**
51
+ * Defines a statically-sized array with elements of a certain type. \
52
+ * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \
53
+ * Fixed arrays much more memory efficient and performant than non-fixed ones.
54
+ *
55
+ * NOTE: If an array will not always have the same length, use the `FieldArray` type.
44
56
  */
45
- declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): T[];
57
+ declare function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(item: T, length: Length): [itemType: T, length: Length];
46
58
  declare class BinaryPacket<T extends Definition> {
47
59
  private readonly packetId;
48
60
  /**
@@ -139,10 +151,13 @@ declare class BinaryPacket<T extends Definition> {
139
151
  private constructor();
140
152
  private read;
141
153
  private write;
154
+ /**
155
+ * Fast write does not support writing dynamically-sized arrays.
156
+ */
142
157
  private fastWrite;
143
158
  /**
144
159
  * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
145
- * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
160
+ * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.
146
161
  */
147
162
  private slowWrite;
148
163
  }
@@ -167,7 +182,7 @@ declare class BinaryPacket<T extends Definition> {
167
182
  * // You can also specify arrays of both "primitive" fields and other BinaryPackets.
168
183
  * const Board = {
169
184
  * numPlayers: Field.UNSIGNED_INT_8,
170
- * cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
185
+ * cells: FieldArray(CellPacket)
171
186
  * }
172
187
  *
173
188
  * // When done with the board definition we can create its BinaryPacket writer/reader.
@@ -190,13 +205,18 @@ declare class BinaryPacket<T extends Definition> {
190
205
  * // ...
191
206
  */
192
207
  type Definition = {
193
- [fieldName: string]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[];
208
+ [fieldName: string]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>>;
194
209
  };
210
+ type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
195
211
  /**
196
212
  * 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. \
197
213
  */
198
214
  type ToJson<T extends Definition> = {
199
- [K in keyof T]: T[K] extends ReadonlyArray<infer Item> ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
215
+ [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>[] & {
216
+ length: Length;
217
+ } : number[] & {
218
+ length: Length;
219
+ } : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
200
220
  };
201
221
 
202
- export { BinaryPacket, type Definition, Field, FieldArray };
222
+ export { BinaryPacket, type Definition, Field, FieldArray, FieldFixedArray };
package/dist/index.js CHANGED
@@ -22,7 +22,8 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  BinaryPacket: () => BinaryPacket,
24
24
  Field: () => Field,
25
- FieldArray: () => FieldArray
25
+ FieldArray: () => FieldArray,
26
+ FieldFixedArray: () => FieldFixedArray
26
27
  });
27
28
  module.exports = __toCommonJS(src_exports);
28
29
 
@@ -59,6 +60,12 @@ var Field = /* @__PURE__ */ ((Field2) => {
59
60
  function FieldArray(item) {
60
61
  return [item];
61
62
  }
63
+ function FieldFixedArray(item, length) {
64
+ if (length < 0 || !Number.isFinite(length)) {
65
+ throw new RangeError("Length of a FixedArray must be a positive integer.");
66
+ }
67
+ return [item, length];
68
+ }
62
69
  var BinaryPacket = class _BinaryPacket {
63
70
  constructor(packetId, definition) {
64
71
  this.packetId = packetId;
@@ -200,7 +207,10 @@ var BinaryPacket = class _BinaryPacket {
200
207
  const result = {};
201
208
  for (const [name, def] of this.entries) {
202
209
  if (Array.isArray(def)) {
203
- const length = readFunctions[0 /* UNSIGNED_INT_8 */](dataIn, offsetPointer.offset++);
210
+ const length = (
211
+ // 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
212
+ def[1] ?? readFunctions[0 /* UNSIGNED_INT_8 */](dataIn, offsetPointer.offset++)
213
+ );
204
214
  const array = Array(length);
205
215
  const itemType = def[0];
206
216
  if (typeof itemType === "object") {
@@ -242,16 +252,28 @@ var BinaryPacket = class _BinaryPacket {
242
252
  );
243
253
  }
244
254
  }
255
+ /**
256
+ * Fast write does not support writing dynamically-sized arrays.
257
+ */
245
258
  fastWrite(buffer, dataOut, offsetPointer, writeFunctions) {
246
259
  for (const [name, def] of this.entries) {
247
- if (typeof def === "object") {
248
- ;
249
- def.fastWrite(
250
- buffer,
251
- dataOut[name],
252
- offsetPointer,
253
- writeFunctions
254
- );
260
+ if (Array.isArray(def)) {
261
+ const itemType = def[0];
262
+ const length = def[1];
263
+ const data = dataOut[name];
264
+ if (typeof itemType === "object") {
265
+ for (let i = 0; i < length; ++i) {
266
+ itemType.fastWrite(buffer, data[i], offsetPointer, writeFunctions);
267
+ }
268
+ } else {
269
+ const itemSize = BYTE_SIZE[itemType];
270
+ for (let i = 0; i < length; ++i) {
271
+ writeFunctions[itemType](buffer, data[i], offsetPointer.offset);
272
+ offsetPointer.offset += itemSize;
273
+ }
274
+ }
275
+ } else if (typeof def === "object") {
276
+ def.fastWrite(buffer, dataOut[name], offsetPointer, writeFunctions);
255
277
  } else {
256
278
  writeFunctions[def](buffer, dataOut[name], offsetPointer.offset);
257
279
  offsetPointer.offset += BYTE_SIZE[def];
@@ -260,23 +282,28 @@ var BinaryPacket = class _BinaryPacket {
260
282
  }
261
283
  /**
262
284
  * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
263
- * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
285
+ * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.
264
286
  */
265
287
  slowWrite(buffer, dataOut, offsetPointer, byteLength, maxByteLength, writeFunctions, growBufferFunction) {
266
288
  for (const [name, def] of this.entries) {
267
289
  const data = dataOut[name];
268
290
  if (Array.isArray(def)) {
269
291
  const length = data.length;
270
- writeFunctions[0 /* UNSIGNED_INT_8 */](buffer, length, offsetPointer.offset);
271
- offsetPointer.offset += 1;
292
+ const isDynamicArray = def[1] === void 0;
293
+ if (isDynamicArray) {
294
+ writeFunctions[0 /* UNSIGNED_INT_8 */](buffer, length, offsetPointer.offset);
295
+ offsetPointer.offset += 1;
296
+ }
272
297
  if (length > 0) {
273
298
  const itemType = def[0];
274
299
  if (typeof itemType === "object") {
275
- const neededBytesForElements = length * itemType.minimumByteLength;
276
- byteLength += neededBytesForElements;
277
- maxByteLength += neededBytesForElements;
278
- if (buffer.byteLength < maxByteLength) {
279
- buffer = growBufferFunction(buffer, maxByteLength);
300
+ if (isDynamicArray) {
301
+ const neededBytesForElements = length * itemType.minimumByteLength;
302
+ byteLength += neededBytesForElements;
303
+ maxByteLength += neededBytesForElements;
304
+ if (buffer.byteLength < maxByteLength) {
305
+ buffer = growBufferFunction(buffer, maxByteLength);
306
+ }
280
307
  }
281
308
  for (const object of data) {
282
309
  writeFunctions[0 /* UNSIGNED_INT_8 */](
@@ -299,11 +326,13 @@ var BinaryPacket = class _BinaryPacket {
299
326
  }
300
327
  } else {
301
328
  const itemSize = BYTE_SIZE[itemType];
302
- const neededBytesForElements = length * itemSize;
303
- byteLength += neededBytesForElements;
304
- maxByteLength += neededBytesForElements;
305
- if (buffer.byteLength < maxByteLength) {
306
- buffer = growBufferFunction(buffer, maxByteLength);
329
+ if (isDynamicArray) {
330
+ const neededBytesForElements = length * itemSize;
331
+ byteLength += neededBytesForElements;
332
+ maxByteLength += neededBytesForElements;
333
+ if (buffer.byteLength < maxByteLength) {
334
+ buffer = growBufferFunction(buffer, maxByteLength);
335
+ }
307
336
  }
308
337
  for (const number of data) {
309
338
  writeFunctions[itemType](buffer, number, offsetPointer.offset);
@@ -343,8 +372,13 @@ function inspectEntries(entries) {
343
372
  let canFastWrite = true;
344
373
  for (const [, type] of entries) {
345
374
  if (Array.isArray(type)) {
346
- minimumByteLength += 1;
347
- canFastWrite = false;
375
+ if (type.length === 2) {
376
+ const itemSize = typeof type[0] === "object" ? type[0].minimumByteLength : BYTE_SIZE[type[0]];
377
+ minimumByteLength += type[1] * itemSize;
378
+ } else {
379
+ minimumByteLength += 1;
380
+ canFastWrite = false;
381
+ }
348
382
  } else if (type instanceof BinaryPacket) {
349
383
  minimumByteLength += type.minimumByteLength;
350
384
  canFastWrite &&= type.canFastWrite;
@@ -366,12 +400,12 @@ BYTE_SIZE[7 /* FLOAT_64 */] = 8;
366
400
  var GET_FUNCTION = Array(8);
367
401
  GET_FUNCTION[0 /* UNSIGNED_INT_8 */] = (view, offset) => view.getUint8(offset);
368
402
  GET_FUNCTION[3 /* INT_8 */] = (view, offset) => view.getInt8(offset);
369
- GET_FUNCTION[1 /* UNSIGNED_INT_16 */] = (view, offset, le) => view.getUint16(offset, le);
370
- GET_FUNCTION[4 /* INT_16 */] = (view, offset, le) => view.getInt16(offset, le);
371
- GET_FUNCTION[2 /* UNSIGNED_INT_32 */] = (view, offset, le) => view.getUint32(offset, le);
372
- GET_FUNCTION[5 /* INT_32 */] = (view, offset, le) => view.getInt32(offset, le);
373
- GET_FUNCTION[6 /* FLOAT_32 */] = (view, offset, le) => view.getFloat32(offset, le);
374
- GET_FUNCTION[7 /* FLOAT_64 */] = (view, offset, le) => view.getFloat64(offset, le);
403
+ GET_FUNCTION[1 /* UNSIGNED_INT_16 */] = (view, offset) => view.getUint16(offset);
404
+ GET_FUNCTION[4 /* INT_16 */] = (view, offset) => view.getInt16(offset);
405
+ GET_FUNCTION[2 /* UNSIGNED_INT_32 */] = (view, offset) => view.getUint32(offset);
406
+ GET_FUNCTION[5 /* INT_32 */] = (view, offset) => view.getInt32(offset);
407
+ GET_FUNCTION[6 /* FLOAT_32 */] = (view, offset) => view.getFloat32(offset);
408
+ GET_FUNCTION[7 /* FLOAT_64 */] = (view, offset) => view.getFloat64(offset);
375
409
  var SET_FUNCTION = Array(8);
376
410
  SET_FUNCTION[0 /* UNSIGNED_INT_8 */] = (view, value, offset) => view.setUint8(offset, value);
377
411
  SET_FUNCTION[3 /* INT_8 */] = (view, value, offset) => view.setInt8(offset, value);
@@ -407,6 +441,7 @@ if (hasNodeBuffers) {
407
441
  0 && (module.exports = {
408
442
  BinaryPacket,
409
443
  Field,
410
- FieldArray
444
+ FieldArray,
445
+ FieldFixedArray
411
446
  });
412
447
  //# 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 } 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 an array of a certain type. \\\r\n * As of now, only arrays with at most 256 elements are supported.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T) {\r\n return [item]\r\n}\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: ArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\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(\r\n dataIn: ArrayBuffer & { buffer?: undefined },\r\n byteOffset: number,\r\n byteLength: number\r\n ) {\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 return this.write(buffer, dataOut, { offset: 0 }, SET_FUNCTION_BUF, growNodeBuffer)\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 return this.write(dataview, dataOut, { offset: 0 }, SET_FUNCTION, growDataView)\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 private readonly entries: Entries\r\n readonly canFastWrite: boolean\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\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.canFastWrite = inspection.canFastWrite\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 = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\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 result[name] = array\r\n } else if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n } else {\r\n // Single primitive (number)\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\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 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 if (this.canFastWrite) {\r\n // If there are no arrays, the minimumByteLength always equals to the full needed byteLength.\r\n // So we can take the fast path, since we know beforehand that the buffer isn't going to grow.\r\n this.fastWrite(buffer, dataOut, offsetPointer, writeFunctions)\r\n return buffer\r\n } else {\r\n // If non-empty arrays are encountered, the buffer must grow.\r\n // If every array is empty, the speed of this path is comparable to the fast path.\r\n return this.slowWrite(\r\n buffer,\r\n dataOut,\r\n offsetPointer,\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n }\r\n }\r\n\r\n private fastWrite<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF\r\n ) {\r\n for (const [name, def] of this.entries) {\r\n if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n ;(def as BinaryPacket<Definition>).fastWrite(\r\n buffer,\r\n dataOut[name] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\r\n } else {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, dataOut[name] as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \\\r\n * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.\r\n */\r\n private slowWrite<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 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 const length = (data as any[]).length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\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 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 for (const object of data as unknown as ToJson<Definition>[]) {\r\n writeFunctions[Field.UNSIGNED_INT_8](\r\n buffer as any,\r\n itemType.packetId,\r\n offsetPointer.offset\r\n )\r\n\r\n offsetPointer.offset += 1\r\n\r\n buffer = itemType.slowWrite(\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 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 // 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 === 'object') {\r\n // Single \"subpacket\"\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, def.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n buffer = def.slowWrite(\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 } else {\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 }\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) // equivalent to { cells: [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]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[]\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\ntype ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends ReadonlyArray<infer Item>\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\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 let canFastWrite = true\r\n\r\n for (const [, type] of entries) {\r\n if (Array.isArray(type)) {\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n canFastWrite = false\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n canFastWrite &&= type.canFastWrite\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, canFastWrite }\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)\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: ((view: DataView, offset: number, littleEndian?: boolean) => number)[] =\r\n Array(8)\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, le) => view.getUint16(offset, le)\r\nGET_FUNCTION[Field.INT_16] = (view, offset, le) => view.getInt16(offset, le)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset, le) => view.getUint32(offset, le)\r\nGET_FUNCTION[Field.INT_32] = (view, offset, le) => view.getInt32(offset, le)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset, le) => view.getFloat32(offset, le)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset, le) => view.getFloat64(offset, le)\r\n\r\nconst SET_FUNCTION: ((view: DataView, value: number, offset: number) => void)[] = Array(8)\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: ((nodeBuffer: Buffer, value: number, offset: number) => void)[] = Array(8)\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: ((nodeBuffer: Buffer, offset: number) => number)[] = Array(8)\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","export 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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,iBAAiB,OAAO,WAAW;AAEzC,SAAS,aAAa,UAAoB,eAAuB;AACtE,QAAM,gBAAgB,IAAI,YAAY,aAAa;AACnD,QAAM,eAAe,KAAK,IAAI,SAAS,YAAY,cAAc,UAAU;AAG3E,MAAI,SAAS,KAAK,MAAM,eAAe,CAAC;AACxC,MAAI,aAAa,eAAe,GAAG,MAAM,EAAE,IAAI,IAAI,aAAa,SAAS,QAAQ,GAAG,MAAM,CAAC;AAG3F,QAAM,SAAS,SAAS;AACxB,WAAS,eAAe;AACxB,MAAI,WAAW,eAAe,QAAQ,MAAM,EAAE,IAAI,IAAI,WAAW,SAAS,QAAQ,QAAQ,MAAM,CAAC;AAEjG,SAAO,IAAI,SAAS,aAAa;AACnC;AAEO,SAAS,eAAe,QAAgB,eAAuB;AACpE,QAAM,YAAY,OAAO,YAAY,aAAa;AAClD,SAAO,KAAK,SAAS;AACrB,SAAO;AACT;;;ADpBO,IAAW,QAAX,kBAAWA,WAAX;AAKL,EAAAA,cAAA,oBAAiB,KAAjB;AAMA,EAAAA,cAAA;AAMA,EAAAA,cAAA;AAMA,EAAAA,cAAA;AAMA,EAAAA,cAAA;AAMA,EAAAA,cAAA;AAKA,EAAAA,cAAA;AAKA,EAAAA,cAAA;AA7CgB,SAAAA;AAAA,GAAA;AAoDX,SAAS,WAAuD,MAAS;AAC9E,SAAO,CAAC,IAAI;AACd;AAEO,IAAM,eAAN,MAAM,cAAmC;AAAA,EAiJtC,YACW,UACjB,YACA;AAFiB;AAGjB,SAAK,UAAU,aAAa,YAAY,UAAU,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B,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAC1E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE5E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AAC/E;","names":["Field"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/buffers.ts"],"sourcesContent":["import { growDataView, growNodeBuffer, hasNodeBuffers } 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\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: ArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\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(\r\n dataIn: ArrayBuffer & { buffer?: undefined },\r\n byteOffset: number,\r\n byteLength: number\r\n ) {\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 return this.write(buffer, dataOut, { offset: 0 }, SET_FUNCTION_BUF, growNodeBuffer)\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 return this.write(dataview, dataOut, { offset: 0 }, SET_FUNCTION, growDataView)\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 private readonly entries: Entries\r\n readonly canFastWrite: boolean\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\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.canFastWrite = inspection.canFastWrite\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 === 'object') {\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 } else {\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 }\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 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 if (this.canFastWrite) {\r\n // If there are no arrays, the minimumByteLength always equals to the full needed byteLength.\r\n // So we can take the fast path, since we know beforehand that the buffer isn't going to grow.\r\n this.fastWrite(buffer, dataOut, offsetPointer, writeFunctions)\r\n return buffer\r\n } else {\r\n // If non-empty arrays are encountered, the buffer must grow.\r\n // If every array is empty, the speed of this path is comparable to the fast path.\r\n return this.slowWrite(\r\n buffer,\r\n dataOut,\r\n offsetPointer,\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n }\r\n }\r\n\r\n /**\r\n * Fast write does not support writing dynamically-sized arrays.\r\n */\r\n private fastWrite<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF\r\n ) {\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n // Statically-sized array\r\n const itemType = def[0]\r\n const length = def[1]!\r\n const data = dataOut[name] as any[]\r\n\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(buffer, data[i] as ToJson<Definition>, offsetPointer, writeFunctions)\r\n }\r\n } else {\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n for (let i = 0; i < length; ++i) {\r\n writeFunctions[itemType](buffer as any, data[i] as number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, dataOut[name] as ToJson<Definition>, offsetPointer, writeFunctions)\r\n } else {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, dataOut[name] as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \\\r\n * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.\r\n */\r\n private slowWrite<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 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 const isDynamicArray = def[1] === undefined\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 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 writeFunctions[Field.UNSIGNED_INT_8](\r\n buffer as any,\r\n itemType.packetId,\r\n offsetPointer.offset\r\n )\r\n\r\n offsetPointer.offset += 1\r\n\r\n buffer = itemType.slowWrite(\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 === 'object') {\r\n // Single \"subpacket\"\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, def.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n buffer = def.slowWrite(\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 } else {\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 }\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]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>>\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\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\ntype 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 : 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 let canFastWrite = true\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 canFastWrite = false\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n canFastWrite &&= type.canFastWrite\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, canFastWrite }\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","export 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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,iBAAiB,OAAO,WAAW;AAEzC,SAAS,aAAa,UAAoB,eAAuB;AACtE,QAAM,gBAAgB,IAAI,YAAY,aAAa;AACnD,QAAM,eAAe,KAAK,IAAI,SAAS,YAAY,cAAc,UAAU;AAG3E,MAAI,SAAS,KAAK,MAAM,eAAe,CAAC;AACxC,MA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AC,MAAM,OAAO,WAAW,KAAK,aAAa,OAAO,MAAM;AAE3F,mBAAiB,gBAAc,IAAI,CAAC,MAAM,OAAO,WAAW,KAAK,cAAc,OAAO,MAAM;AAC9F;AAEA,IAAM,mBAAmB,MAAM,CAAC;AAEhC,IAAI,gBAAgB;AAClB,mBAAiB,sBAAoB,IAAI,CAAC,MAAM,WAAW,KAAK,UAAU,MAAM;AAChF,mBAAiB,aAAW,IAAI,CAAC,MAAM,WAAW,KAAK,SAAS,MAAM;AAEtE,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE1E,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAC1E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE5E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AAC/E;","names":["Field"]}
package/dist/index.mjs CHANGED
@@ -31,6 +31,12 @@ var Field = /* @__PURE__ */ ((Field2) => {
31
31
  function FieldArray(item) {
32
32
  return [item];
33
33
  }
34
+ function FieldFixedArray(item, length) {
35
+ if (length < 0 || !Number.isFinite(length)) {
36
+ throw new RangeError("Length of a FixedArray must be a positive integer.");
37
+ }
38
+ return [item, length];
39
+ }
34
40
  var BinaryPacket = class _BinaryPacket {
35
41
  constructor(packetId, definition) {
36
42
  this.packetId = packetId;
@@ -172,7 +178,10 @@ var BinaryPacket = class _BinaryPacket {
172
178
  const result = {};
173
179
  for (const [name, def] of this.entries) {
174
180
  if (Array.isArray(def)) {
175
- const length = readFunctions[0 /* UNSIGNED_INT_8 */](dataIn, offsetPointer.offset++);
181
+ const length = (
182
+ // 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
183
+ def[1] ?? readFunctions[0 /* UNSIGNED_INT_8 */](dataIn, offsetPointer.offset++)
184
+ );
176
185
  const array = Array(length);
177
186
  const itemType = def[0];
178
187
  if (typeof itemType === "object") {
@@ -214,16 +223,28 @@ var BinaryPacket = class _BinaryPacket {
214
223
  );
215
224
  }
216
225
  }
226
+ /**
227
+ * Fast write does not support writing dynamically-sized arrays.
228
+ */
217
229
  fastWrite(buffer, dataOut, offsetPointer, writeFunctions) {
218
230
  for (const [name, def] of this.entries) {
219
- if (typeof def === "object") {
220
- ;
221
- def.fastWrite(
222
- buffer,
223
- dataOut[name],
224
- offsetPointer,
225
- writeFunctions
226
- );
231
+ if (Array.isArray(def)) {
232
+ const itemType = def[0];
233
+ const length = def[1];
234
+ const data = dataOut[name];
235
+ if (typeof itemType === "object") {
236
+ for (let i = 0; i < length; ++i) {
237
+ itemType.fastWrite(buffer, data[i], offsetPointer, writeFunctions);
238
+ }
239
+ } else {
240
+ const itemSize = BYTE_SIZE[itemType];
241
+ for (let i = 0; i < length; ++i) {
242
+ writeFunctions[itemType](buffer, data[i], offsetPointer.offset);
243
+ offsetPointer.offset += itemSize;
244
+ }
245
+ }
246
+ } else if (typeof def === "object") {
247
+ def.fastWrite(buffer, dataOut[name], offsetPointer, writeFunctions);
227
248
  } else {
228
249
  writeFunctions[def](buffer, dataOut[name], offsetPointer.offset);
229
250
  offsetPointer.offset += BYTE_SIZE[def];
@@ -232,23 +253,28 @@ var BinaryPacket = class _BinaryPacket {
232
253
  }
233
254
  /**
234
255
  * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
235
- * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
256
+ * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.
236
257
  */
237
258
  slowWrite(buffer, dataOut, offsetPointer, byteLength, maxByteLength, writeFunctions, growBufferFunction) {
238
259
  for (const [name, def] of this.entries) {
239
260
  const data = dataOut[name];
240
261
  if (Array.isArray(def)) {
241
262
  const length = data.length;
242
- writeFunctions[0 /* UNSIGNED_INT_8 */](buffer, length, offsetPointer.offset);
243
- offsetPointer.offset += 1;
263
+ const isDynamicArray = def[1] === void 0;
264
+ if (isDynamicArray) {
265
+ writeFunctions[0 /* UNSIGNED_INT_8 */](buffer, length, offsetPointer.offset);
266
+ offsetPointer.offset += 1;
267
+ }
244
268
  if (length > 0) {
245
269
  const itemType = def[0];
246
270
  if (typeof itemType === "object") {
247
- const neededBytesForElements = length * itemType.minimumByteLength;
248
- byteLength += neededBytesForElements;
249
- maxByteLength += neededBytesForElements;
250
- if (buffer.byteLength < maxByteLength) {
251
- buffer = growBufferFunction(buffer, maxByteLength);
271
+ if (isDynamicArray) {
272
+ const neededBytesForElements = length * itemType.minimumByteLength;
273
+ byteLength += neededBytesForElements;
274
+ maxByteLength += neededBytesForElements;
275
+ if (buffer.byteLength < maxByteLength) {
276
+ buffer = growBufferFunction(buffer, maxByteLength);
277
+ }
252
278
  }
253
279
  for (const object of data) {
254
280
  writeFunctions[0 /* UNSIGNED_INT_8 */](
@@ -271,11 +297,13 @@ var BinaryPacket = class _BinaryPacket {
271
297
  }
272
298
  } else {
273
299
  const itemSize = BYTE_SIZE[itemType];
274
- const neededBytesForElements = length * itemSize;
275
- byteLength += neededBytesForElements;
276
- maxByteLength += neededBytesForElements;
277
- if (buffer.byteLength < maxByteLength) {
278
- buffer = growBufferFunction(buffer, maxByteLength);
300
+ if (isDynamicArray) {
301
+ const neededBytesForElements = length * itemSize;
302
+ byteLength += neededBytesForElements;
303
+ maxByteLength += neededBytesForElements;
304
+ if (buffer.byteLength < maxByteLength) {
305
+ buffer = growBufferFunction(buffer, maxByteLength);
306
+ }
279
307
  }
280
308
  for (const number of data) {
281
309
  writeFunctions[itemType](buffer, number, offsetPointer.offset);
@@ -315,8 +343,13 @@ function inspectEntries(entries) {
315
343
  let canFastWrite = true;
316
344
  for (const [, type] of entries) {
317
345
  if (Array.isArray(type)) {
318
- minimumByteLength += 1;
319
- canFastWrite = false;
346
+ if (type.length === 2) {
347
+ const itemSize = typeof type[0] === "object" ? type[0].minimumByteLength : BYTE_SIZE[type[0]];
348
+ minimumByteLength += type[1] * itemSize;
349
+ } else {
350
+ minimumByteLength += 1;
351
+ canFastWrite = false;
352
+ }
320
353
  } else if (type instanceof BinaryPacket) {
321
354
  minimumByteLength += type.minimumByteLength;
322
355
  canFastWrite &&= type.canFastWrite;
@@ -338,12 +371,12 @@ BYTE_SIZE[7 /* FLOAT_64 */] = 8;
338
371
  var GET_FUNCTION = Array(8);
339
372
  GET_FUNCTION[0 /* UNSIGNED_INT_8 */] = (view, offset) => view.getUint8(offset);
340
373
  GET_FUNCTION[3 /* INT_8 */] = (view, offset) => view.getInt8(offset);
341
- GET_FUNCTION[1 /* UNSIGNED_INT_16 */] = (view, offset, le) => view.getUint16(offset, le);
342
- GET_FUNCTION[4 /* INT_16 */] = (view, offset, le) => view.getInt16(offset, le);
343
- GET_FUNCTION[2 /* UNSIGNED_INT_32 */] = (view, offset, le) => view.getUint32(offset, le);
344
- GET_FUNCTION[5 /* INT_32 */] = (view, offset, le) => view.getInt32(offset, le);
345
- GET_FUNCTION[6 /* FLOAT_32 */] = (view, offset, le) => view.getFloat32(offset, le);
346
- GET_FUNCTION[7 /* FLOAT_64 */] = (view, offset, le) => view.getFloat64(offset, le);
374
+ GET_FUNCTION[1 /* UNSIGNED_INT_16 */] = (view, offset) => view.getUint16(offset);
375
+ GET_FUNCTION[4 /* INT_16 */] = (view, offset) => view.getInt16(offset);
376
+ GET_FUNCTION[2 /* UNSIGNED_INT_32 */] = (view, offset) => view.getUint32(offset);
377
+ GET_FUNCTION[5 /* INT_32 */] = (view, offset) => view.getInt32(offset);
378
+ GET_FUNCTION[6 /* FLOAT_32 */] = (view, offset) => view.getFloat32(offset);
379
+ GET_FUNCTION[7 /* FLOAT_64 */] = (view, offset) => view.getFloat64(offset);
347
380
  var SET_FUNCTION = Array(8);
348
381
  SET_FUNCTION[0 /* UNSIGNED_INT_8 */] = (view, value, offset) => view.setUint8(offset, value);
349
382
  SET_FUNCTION[3 /* INT_8 */] = (view, value, offset) => view.setInt8(offset, value);
@@ -378,6 +411,7 @@ if (hasNodeBuffers) {
378
411
  export {
379
412
  BinaryPacket,
380
413
  Field,
381
- FieldArray
414
+ FieldArray,
415
+ FieldFixedArray
382
416
  };
383
417
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/buffers.ts","../src/index.ts"],"sourcesContent":["export 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 } 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 an array of a certain type. \\\r\n * As of now, only arrays with at most 256 elements are supported.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T) {\r\n return [item]\r\n}\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: ArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\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(\r\n dataIn: ArrayBuffer & { buffer?: undefined },\r\n byteOffset: number,\r\n byteLength: number\r\n ) {\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 return this.write(buffer, dataOut, { offset: 0 }, SET_FUNCTION_BUF, growNodeBuffer)\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 return this.write(dataview, dataOut, { offset: 0 }, SET_FUNCTION, growDataView)\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 private readonly entries: Entries\r\n readonly canFastWrite: boolean\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\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.canFastWrite = inspection.canFastWrite\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 = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\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 result[name] = array\r\n } else if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n } else {\r\n // Single primitive (number)\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\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 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 if (this.canFastWrite) {\r\n // If there are no arrays, the minimumByteLength always equals to the full needed byteLength.\r\n // So we can take the fast path, since we know beforehand that the buffer isn't going to grow.\r\n this.fastWrite(buffer, dataOut, offsetPointer, writeFunctions)\r\n return buffer\r\n } else {\r\n // If non-empty arrays are encountered, the buffer must grow.\r\n // If every array is empty, the speed of this path is comparable to the fast path.\r\n return this.slowWrite(\r\n buffer,\r\n dataOut,\r\n offsetPointer,\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n }\r\n }\r\n\r\n private fastWrite<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF\r\n ) {\r\n for (const [name, def] of this.entries) {\r\n if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n ;(def as BinaryPacket<Definition>).fastWrite(\r\n buffer,\r\n dataOut[name] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\r\n } else {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, dataOut[name] as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \\\r\n * But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.\r\n */\r\n private slowWrite<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 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 const length = (data as any[]).length\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, length, offsetPointer.offset)\r\n offsetPointer.offset += 1\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 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 for (const object of data as unknown as ToJson<Definition>[]) {\r\n writeFunctions[Field.UNSIGNED_INT_8](\r\n buffer as any,\r\n itemType.packetId,\r\n offsetPointer.offset\r\n )\r\n\r\n offsetPointer.offset += 1\r\n\r\n buffer = itemType.slowWrite(\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 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 // 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 === 'object') {\r\n // Single \"subpacket\"\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, def.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n buffer = def.slowWrite(\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 } else {\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 }\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) // equivalent to { cells: [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]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[]\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\ntype ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends ReadonlyArray<infer Item>\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\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 let canFastWrite = true\r\n\r\n for (const [, type] of entries) {\r\n if (Array.isArray(type)) {\r\n // Adding 1 byte to serialize the array length\r\n minimumByteLength += 1\r\n canFastWrite = false\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n canFastWrite &&= type.canFastWrite\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, canFastWrite }\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)\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: ((view: DataView, offset: number, littleEndian?: boolean) => number)[] =\r\n Array(8)\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, le) => view.getUint16(offset, le)\r\nGET_FUNCTION[Field.INT_16] = (view, offset, le) => view.getInt16(offset, le)\r\n\r\nGET_FUNCTION[Field.UNSIGNED_INT_32] = (view, offset, le) => view.getUint32(offset, le)\r\nGET_FUNCTION[Field.INT_32] = (view, offset, le) => view.getInt32(offset, le)\r\nGET_FUNCTION[Field.FLOAT_32] = (view, offset, le) => view.getFloat32(offset, le)\r\n\r\nGET_FUNCTION[Field.FLOAT_64] = (view, offset, le) => view.getFloat64(offset, le)\r\n\r\nconst SET_FUNCTION: ((view: DataView, value: number, offset: number) => void)[] = Array(8)\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: ((nodeBuffer: Buffer, value: number, offset: number) => void)[] = Array(8)\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: ((nodeBuffer: Buffer, offset: number) => number)[] = Array(8)\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"],"mappings":";AAAO,IAAM,iBAAiB,OAAO,WAAW;AAEzC,SAAS,aAAa,UAAoB,eAAuB;AACtE,QAAM,gBAAgB,IAAI,YAAY,aAAa;AACnD,QAAM,eAAe,KAAK,IAAI,SAAS,YAAY,cAAc,UAAU;AAG3E,MAAI,SAAS,KAAK,MAAM,eAAe,CAAC;AACxC,MAAI,aAAa,eAAe,GAAG,MAAM,EAAE,IAAI,IAAI,aAAa,SAAS,QAAQ,GAAG,MAAM,CAAC;AAG3F,QAAM,SAAS,SAAS;AACxB,WAAS,eAAe;AACxB,MAAI,WAAW,eAAe,QAAQ,MAAM,EAAE,IAAI,IAAI,WAAW,SAAS,QAAQ,QAAQ,MAAM,CAAC;AAEjG,SAAO,IAAI,SAAS,aAAa;AACnC;AAEO,SAAS,eAAe,QAAgB,eAAuB;AACpE,QAAM,YAAY,OAAO,YAAY,aAAa;AAClD,SAAO,KAAK,SAAS;AACrB,SAAO;AACT;;;ACpBO,IAAW,QAAX,kBAAWA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AW,KAAK,cAAc,OAAO,MAAM;AAC9F;AAEA,IAAM,mBAAuE,MAAM,CAAC;AAEpF,IAAI,gBAAgB;AAClB,mBAAiB,sBAAoB,IAAI,CAAC,MAAM,WAAW,KAAK,UAAU,MAAM;AAChF,mBAAiB,aAAW,IAAI,CAAC,MAAM,WAAW,KAAK,SAAS,MAAM;AAEtE,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE1E,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAC1E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE5E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AAC/E;","names":["Field"]}
1
+ {"version":3,"sources":["../src/buffers.ts","../src/index.ts"],"sourcesContent":["export 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 } 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\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: ArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\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(\r\n dataIn: ArrayBuffer & { buffer?: undefined },\r\n byteOffset: number,\r\n byteLength: number\r\n ) {\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 return this.write(buffer, dataOut, { offset: 0 }, SET_FUNCTION_BUF, growNodeBuffer)\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 return this.write(dataview, dataOut, { offset: 0 }, SET_FUNCTION, growDataView)\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 private readonly entries: Entries\r\n readonly canFastWrite: boolean\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\r\n this.minimumByteLength = inspection.minimumByteLength\r\n this.canFastWrite = inspection.canFastWrite\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 === 'object') {\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 } else {\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 }\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 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 if (this.canFastWrite) {\r\n // If there are no arrays, the minimumByteLength always equals to the full needed byteLength.\r\n // So we can take the fast path, since we know beforehand that the buffer isn't going to grow.\r\n this.fastWrite(buffer, dataOut, offsetPointer, writeFunctions)\r\n return buffer\r\n } else {\r\n // If non-empty arrays are encountered, the buffer must grow.\r\n // If every array is empty, the speed of this path is comparable to the fast path.\r\n return this.slowWrite(\r\n buffer,\r\n dataOut,\r\n offsetPointer,\r\n this.minimumByteLength,\r\n this.minimumByteLength,\r\n writeFunctions,\r\n growBufferFunction\r\n )\r\n }\r\n }\r\n\r\n /**\r\n * Fast write does not support writing dynamically-sized arrays.\r\n */\r\n private fastWrite<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n writeFunctions: typeof SET_FUNCTION | typeof SET_FUNCTION_BUF\r\n ) {\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n // Statically-sized array\r\n const itemType = def[0]\r\n const length = def[1]!\r\n const data = dataOut[name] as any[]\r\n\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(buffer, data[i] as ToJson<Definition>, offsetPointer, writeFunctions)\r\n }\r\n } else {\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n for (let i = 0; i < length; ++i) {\r\n writeFunctions[itemType](buffer as any, data[i] as number, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'object') {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, dataOut[name] as ToJson<Definition>, offsetPointer, writeFunctions)\r\n } else {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, dataOut[name] as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * The slow writing path tries writing data into the buffer as fast as the fast writing path does. \\\r\n * But, if a non-empty dynamically-sized array is encountered, the buffer needs to grow, slightly reducing performance.\r\n */\r\n private slowWrite<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 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 const isDynamicArray = def[1] === undefined\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 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 writeFunctions[Field.UNSIGNED_INT_8](\r\n buffer as any,\r\n itemType.packetId,\r\n offsetPointer.offset\r\n )\r\n\r\n offsetPointer.offset += 1\r\n\r\n buffer = itemType.slowWrite(\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 === 'object') {\r\n // Single \"subpacket\"\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, def.packetId, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n buffer = def.slowWrite(\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 } else {\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 }\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]: MaybeArray<Field> | MaybeArray<BinaryPacket<Definition>>\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\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\ntype 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 : 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 let canFastWrite = true\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 canFastWrite = false\r\n }\r\n } else if (type instanceof BinaryPacket) {\r\n minimumByteLength += type.minimumByteLength\r\n canFastWrite &&= type.canFastWrite\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, canFastWrite }\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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OAAO,WACtD,KAAK,cAAc,OAAO,MAAM;AAClC,mBAAiB,cAAY,IAAI,CAAC,MAAM,OAAO,WAAW,KAAK,aAAa,OAAO,MAAM;AAEzF,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,OAAO,WACtD,KAAK,cAAc,OAAO,MAAM;AAClC,mBAAiB,cAAY,IAAI,CAAC,MAAM,OAAO,WAAW,KAAK,aAAa,OAAO,MAAM;AACzF,mBAAiB,gBAAc,IAAI,CAAC,MAAM,OAAO,WAAW,KAAK,aAAa,OAAO,MAAM;AAE3F,mBAAiB,gBAAc,IAAI,CAAC,MAAM,OAAO,WAAW,KAAK,cAAc,OAAO,MAAM;AAC9F;AAEA,IAAM,mBAAmB,MAAM,CAAC;AAEhC,IAAI,gBAAgB;AAClB,mBAAiB,sBAAoB,IAAI,CAAC,MAAM,WAAW,KAAK,UAAU,MAAM;AAChF,mBAAiB,aAAW,IAAI,CAAC,MAAM,WAAW,KAAK,SAAS,MAAM;AAEtE,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE1E,mBAAiB,uBAAqB,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AACpF,mBAAiB,cAAY,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAC1E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM;AAE5E,mBAAiB,gBAAc,IAAI,CAAC,MAAM,WAAW,KAAK,aAAa,MAAM;AAC/E;","names":["Field"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "binary-packet",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
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",
@@ -11,7 +11,8 @@
11
11
  "scripts": {
12
12
  "build": "tsup",
13
13
  "test": "node -r ts-node/register/transpile-only src/tests/reads.test.ts && node -r ts-node/register/transpile-only src/tests/writes.test.ts",
14
- "benchmark": "node -r ts-node/register/transpile-only src/tests/benchmark.test.ts"
14
+ "benchmark": "node -r ts-node/register/transpile-only src/tests/benchmark.test.ts",
15
+ "lint": "eslint"
15
16
  },
16
17
  "keywords": [
17
18
  "binary-packet",
@@ -45,13 +46,15 @@
45
46
  "license": "Apache-2.0",
46
47
  "devDependencies": {
47
48
  "colors": "^1.4.0",
49
+ "eslint": "^9.12.0",
48
50
  "msgpackr": "^1.11.0",
49
51
  "prettier": "^3.3.3",
50
52
  "prettier-plugin-organize-imports": "^4.1.0",
51
53
  "restructure": "^3.0.2",
52
54
  "ts-node": "^10.9.2",
53
55
  "tsup": "^8.3.0",
54
- "typescript": "^5.6.2"
56
+ "typescript": "^5.6.2",
57
+ "typescript-eslint": "^8.8.1"
55
58
  },
56
59
  "engines": {
57
60
  "node": ">=16"