binary-packet 1.0.7 → 1.0.8
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 +43 -1
- package/dist/index.d.mts +51 -8
- package/dist/index.d.ts +51 -8
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -19,6 +19,8 @@ Bun: \
|
|
|
19
19
|
Define the structure of the packets through unique Packet IDs and "schema" objects. \
|
|
20
20
|
This "schema" object is simply called `Definition` and defines the shape of a packet: specifically its `fields` and their `types`.
|
|
21
21
|
|
|
22
|
+
### Fields / Data types
|
|
23
|
+
|
|
22
24
|
Currently, these kinds of `fields` are supported:
|
|
23
25
|
| Type | Description | Values | Size (bytes) |
|
|
24
26
|
|------|-------------|--------------|--------------|
|
|
@@ -38,12 +40,19 @@ Currently, these kinds of `fields` are supported:
|
|
|
38
40
|
As shown, both arrays and nested objects ("subpackets") are supported. \
|
|
39
41
|
Note: `FieldFixedArray` is much more memory efficient and performant than `FieldArray`, but require a pre-defined length.
|
|
40
42
|
|
|
43
|
+
### Pattern matching
|
|
44
|
+
|
|
45
|
+
The library exposes an easy way to "pattern match" packets of a **yet-unknown-type** in a type-safe manner through a `visitor` pattern. \
|
|
46
|
+
For an example, search for "**pattern matching**" in the examples below.
|
|
47
|
+
|
|
41
48
|
## Usage Examples
|
|
42
49
|
|
|
50
|
+
### Example: (incomplete) definition of a simplistic board game
|
|
51
|
+
|
|
43
52
|
```typescript
|
|
44
53
|
import { BinaryPacket, Field, FieldArray } from 'binary-packet'
|
|
45
54
|
|
|
46
|
-
//
|
|
55
|
+
// Suppose we have a game board where each cell is a square and is one unit big.
|
|
47
56
|
// A cell can be then defined by its X and Y coordinates.
|
|
48
57
|
// For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
|
|
49
58
|
const Cell = {
|
|
@@ -103,6 +112,39 @@ assert(board.cells[1].x === 1)
|
|
|
103
112
|
assert(board.cells[1].y === 1)
|
|
104
113
|
```
|
|
105
114
|
|
|
115
|
+
### Example: pattern matching
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import assert from 'assert/strict'
|
|
119
|
+
import { BinaryPacket, Field } from 'binary-packet'
|
|
120
|
+
|
|
121
|
+
// Packet A definition
|
|
122
|
+
const A = BinaryPacket.define(1)
|
|
123
|
+
|
|
124
|
+
// Packet B definition: This is the kind of packets that we care about in this example!
|
|
125
|
+
const B = BinaryPacket.define(2, { data: Field.UNSIGNED_INT_8 })
|
|
126
|
+
|
|
127
|
+
// Packet C definition
|
|
128
|
+
const C = BinaryPacket.define(3)
|
|
129
|
+
|
|
130
|
+
// Assume the following packet comes from the network or, for some other reason, is a buffer we do not know anything about.
|
|
131
|
+
const buffer = B.writeNodeBuffer({ data: 255 })
|
|
132
|
+
|
|
133
|
+
BinaryPacket.visitNodeBuffer(
|
|
134
|
+
buffer,
|
|
135
|
+
|
|
136
|
+
A.visitor(() => assert(false, 'Erroneously accepted visitor A')),
|
|
137
|
+
|
|
138
|
+
B.visitor(packet => {
|
|
139
|
+
// Do something with the packet
|
|
140
|
+
assert.equal(packet.data, 255)
|
|
141
|
+
console.log('Accepted visitor B:', packet)
|
|
142
|
+
}),
|
|
143
|
+
|
|
144
|
+
C.visitor(() => assert(false, 'Erroneously accepted visitor C'))
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
106
148
|
## Benchmarks & Alternatives
|
|
107
149
|
|
|
108
150
|
Benchmarks are not always meant to be taken seriously. \
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \
|
|
3
|
+
* This is needed because the `DataView` constructor explicitly requires a "true" ArrayBuffer, or else it throws.
|
|
4
|
+
*/
|
|
5
|
+
type TrueArrayBuffer = ArrayBuffer & {
|
|
6
|
+
buffer?: undefined;
|
|
7
|
+
};
|
|
8
|
+
|
|
1
9
|
declare const enum Field {
|
|
2
10
|
/**
|
|
3
11
|
* Defines a 1 byte (8 bits) unsigned integer field. \
|
|
@@ -68,6 +76,11 @@ type BitFlags = (string[] | ReadonlyArray<string>) & {
|
|
|
68
76
|
declare function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray): {
|
|
69
77
|
flags: FlagsArray;
|
|
70
78
|
};
|
|
79
|
+
/**
|
|
80
|
+
* Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \
|
|
81
|
+
* Used in the `BinaryPacket::visit` static method to perform a sort of "pattern matching" on an incoming packet (of yet unknown type) buffer.
|
|
82
|
+
*/
|
|
83
|
+
type Visitor = [BinaryPacket<Definition>, (packet: any) => void];
|
|
71
84
|
declare class BinaryPacket<T extends Definition> {
|
|
72
85
|
private readonly packetId;
|
|
73
86
|
/**
|
|
@@ -96,7 +109,30 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
96
109
|
* NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \
|
|
97
110
|
* NOTE: For more information read the `readArrayBuffer` method documentation.
|
|
98
111
|
*/
|
|
99
|
-
static readPacketIdArrayBuffer(arraybuffer:
|
|
112
|
+
static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number): number;
|
|
113
|
+
/**
|
|
114
|
+
* Visits and "pattern matches" the given Buffer through the given visitors. \
|
|
115
|
+
* The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
116
|
+
*
|
|
117
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
118
|
+
*/
|
|
119
|
+
static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]): void;
|
|
120
|
+
/**
|
|
121
|
+
* Visits and "pattern matches" the given DataView through the given visitors. \
|
|
122
|
+
* The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
123
|
+
*
|
|
124
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
125
|
+
*/
|
|
126
|
+
static visitDataView(dataview: DataView, ...visitors: Visitor[]): void;
|
|
127
|
+
/**
|
|
128
|
+
* Visits and "pattern matches" the given ArrayBuffer through the given visitors. \
|
|
129
|
+
* The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
130
|
+
*
|
|
131
|
+
* NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \
|
|
132
|
+
* NOTE: For more information read the `readArrayBuffer` method documentation. \
|
|
133
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
134
|
+
*/
|
|
135
|
+
static visitArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number, byteLength: number, ...visitors: Visitor[]): void;
|
|
100
136
|
/**
|
|
101
137
|
* Reads/deserializes from the given Buffer. \
|
|
102
138
|
* Method available ONLY on NodeJS and Bun.
|
|
@@ -129,9 +165,7 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
129
165
|
* NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \
|
|
130
166
|
* NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.
|
|
131
167
|
*/
|
|
132
|
-
readArrayBuffer(dataIn:
|
|
133
|
-
buffer?: undefined;
|
|
134
|
-
}, byteOffset: number, byteLength: number): ToJson<T>;
|
|
168
|
+
readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number): ToJson<T>;
|
|
135
169
|
/**
|
|
136
170
|
* Writes/serializes the given object into a Buffer. \
|
|
137
171
|
* Method available ONLY on NodeJS and Bun.
|
|
@@ -158,10 +192,19 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
158
192
|
byteLength: number;
|
|
159
193
|
byteOffset: number;
|
|
160
194
|
};
|
|
195
|
+
/**
|
|
196
|
+
* Creates a "visitor" object for this BinaryPacket definition. \
|
|
197
|
+
* Used when visiting and "pattern matching" buffers with the `BinaryPacket::visit` static utility methods. \
|
|
198
|
+
*
|
|
199
|
+
* For more information read the `BinaryPacket::visitNodeBuffer` documentation. \
|
|
200
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
201
|
+
*/
|
|
202
|
+
visitor(onVisit: (packet: ToJson<T>) => void): Visitor;
|
|
161
203
|
private readonly entries;
|
|
162
204
|
readonly canFastWrite: boolean;
|
|
163
205
|
readonly minimumByteLength: number;
|
|
164
206
|
private constructor();
|
|
207
|
+
private static visit;
|
|
165
208
|
private read;
|
|
166
209
|
private write;
|
|
167
210
|
/**
|
|
@@ -223,6 +266,9 @@ type Definition = {
|
|
|
223
266
|
};
|
|
224
267
|
};
|
|
225
268
|
type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
|
|
269
|
+
type BitFlagsToJson<FlagsArray extends BitFlags> = {
|
|
270
|
+
[key in FlagsArray[number]]: boolean;
|
|
271
|
+
};
|
|
226
272
|
/**
|
|
227
273
|
* 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. \
|
|
228
274
|
*/
|
|
@@ -235,8 +281,5 @@ type ToJson<T extends Definition> = {
|
|
|
235
281
|
flags: infer FlagsArray extends BitFlags;
|
|
236
282
|
} ? BitFlagsToJson<FlagsArray> : number;
|
|
237
283
|
};
|
|
238
|
-
type BitFlagsToJson<FlagsArray extends BitFlags> = {
|
|
239
|
-
[key in FlagsArray[number]]: boolean;
|
|
240
|
-
};
|
|
241
284
|
|
|
242
|
-
export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray };
|
|
285
|
+
export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, type ToJson };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \
|
|
3
|
+
* This is needed because the `DataView` constructor explicitly requires a "true" ArrayBuffer, or else it throws.
|
|
4
|
+
*/
|
|
5
|
+
type TrueArrayBuffer = ArrayBuffer & {
|
|
6
|
+
buffer?: undefined;
|
|
7
|
+
};
|
|
8
|
+
|
|
1
9
|
declare const enum Field {
|
|
2
10
|
/**
|
|
3
11
|
* Defines a 1 byte (8 bits) unsigned integer field. \
|
|
@@ -68,6 +76,11 @@ type BitFlags = (string[] | ReadonlyArray<string>) & {
|
|
|
68
76
|
declare function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray): {
|
|
69
77
|
flags: FlagsArray;
|
|
70
78
|
};
|
|
79
|
+
/**
|
|
80
|
+
* Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \
|
|
81
|
+
* Used in the `BinaryPacket::visit` static method to perform a sort of "pattern matching" on an incoming packet (of yet unknown type) buffer.
|
|
82
|
+
*/
|
|
83
|
+
type Visitor = [BinaryPacket<Definition>, (packet: any) => void];
|
|
71
84
|
declare class BinaryPacket<T extends Definition> {
|
|
72
85
|
private readonly packetId;
|
|
73
86
|
/**
|
|
@@ -96,7 +109,30 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
96
109
|
* NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \
|
|
97
110
|
* NOTE: For more information read the `readArrayBuffer` method documentation.
|
|
98
111
|
*/
|
|
99
|
-
static readPacketIdArrayBuffer(arraybuffer:
|
|
112
|
+
static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number): number;
|
|
113
|
+
/**
|
|
114
|
+
* Visits and "pattern matches" the given Buffer through the given visitors. \
|
|
115
|
+
* The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
116
|
+
*
|
|
117
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
118
|
+
*/
|
|
119
|
+
static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]): void;
|
|
120
|
+
/**
|
|
121
|
+
* Visits and "pattern matches" the given DataView through the given visitors. \
|
|
122
|
+
* The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
123
|
+
*
|
|
124
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
125
|
+
*/
|
|
126
|
+
static visitDataView(dataview: DataView, ...visitors: Visitor[]): void;
|
|
127
|
+
/**
|
|
128
|
+
* Visits and "pattern matches" the given ArrayBuffer through the given visitors. \
|
|
129
|
+
* The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.
|
|
130
|
+
*
|
|
131
|
+
* NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \
|
|
132
|
+
* NOTE: For more information read the `readArrayBuffer` method documentation. \
|
|
133
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
134
|
+
*/
|
|
135
|
+
static visitArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number, byteLength: number, ...visitors: Visitor[]): void;
|
|
100
136
|
/**
|
|
101
137
|
* Reads/deserializes from the given Buffer. \
|
|
102
138
|
* Method available ONLY on NodeJS and Bun.
|
|
@@ -129,9 +165,7 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
129
165
|
* NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \
|
|
130
166
|
* NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.
|
|
131
167
|
*/
|
|
132
|
-
readArrayBuffer(dataIn:
|
|
133
|
-
buffer?: undefined;
|
|
134
|
-
}, byteOffset: number, byteLength: number): ToJson<T>;
|
|
168
|
+
readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number): ToJson<T>;
|
|
135
169
|
/**
|
|
136
170
|
* Writes/serializes the given object into a Buffer. \
|
|
137
171
|
* Method available ONLY on NodeJS and Bun.
|
|
@@ -158,10 +192,19 @@ declare class BinaryPacket<T extends Definition> {
|
|
|
158
192
|
byteLength: number;
|
|
159
193
|
byteOffset: number;
|
|
160
194
|
};
|
|
195
|
+
/**
|
|
196
|
+
* Creates a "visitor" object for this BinaryPacket definition. \
|
|
197
|
+
* Used when visiting and "pattern matching" buffers with the `BinaryPacket::visit` static utility methods. \
|
|
198
|
+
*
|
|
199
|
+
* For more information read the `BinaryPacket::visitNodeBuffer` documentation. \
|
|
200
|
+
* NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.
|
|
201
|
+
*/
|
|
202
|
+
visitor(onVisit: (packet: ToJson<T>) => void): Visitor;
|
|
161
203
|
private readonly entries;
|
|
162
204
|
readonly canFastWrite: boolean;
|
|
163
205
|
readonly minimumByteLength: number;
|
|
164
206
|
private constructor();
|
|
207
|
+
private static visit;
|
|
165
208
|
private read;
|
|
166
209
|
private write;
|
|
167
210
|
/**
|
|
@@ -223,6 +266,9 @@ type Definition = {
|
|
|
223
266
|
};
|
|
224
267
|
};
|
|
225
268
|
type MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number];
|
|
269
|
+
type BitFlagsToJson<FlagsArray extends BitFlags> = {
|
|
270
|
+
[key in FlagsArray[number]]: boolean;
|
|
271
|
+
};
|
|
226
272
|
/**
|
|
227
273
|
* 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. \
|
|
228
274
|
*/
|
|
@@ -235,8 +281,5 @@ type ToJson<T extends Definition> = {
|
|
|
235
281
|
flags: infer FlagsArray extends BitFlags;
|
|
236
282
|
} ? BitFlagsToJson<FlagsArray> : number;
|
|
237
283
|
};
|
|
238
|
-
type BitFlagsToJson<FlagsArray extends BitFlags> = {
|
|
239
|
-
[key in FlagsArray[number]]: boolean;
|
|
240
|
-
};
|
|
241
284
|
|
|
242
|
-
export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray };
|
|
285
|
+
export { BinaryPacket, type Definition, Field, FieldArray, FieldBitFlags, FieldFixedArray, type ToJson };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var D=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var S=(
|
|
1
|
+
"use strict";var D=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var S=(r,e)=>{for(var t in e)D(r,t,{get:e[t],enumerable:!0})},L=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of A(e))!b.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(i=w(e,n))||i.enumerable});return r};var G=r=>L(D({},"__esModule",{value:!0}),r);var J={};S(J,{BinaryPacket:()=>g,Field:()=>U,FieldArray:()=>v,FieldBitFlags:()=>k,FieldFixedArray:()=>V});module.exports=G(J);var F=typeof Buffer=="function";function E(r,e){let t=new ArrayBuffer(e),i=Math.min(r.byteLength,t.byteLength),n=Math.trunc(i/8);new Float64Array(t,0,n).set(new Float64Array(r.buffer,0,n));let f=n*8;return n=i-f,new Uint8Array(t,f,n).set(new Uint8Array(r.buffer,f,n)),new DataView(t)}function h(r,e){let t=Buffer.allocUnsafe(e);return r.copy(t),t}var U=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(U||{});function v(r){return[r]}function V(r,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[r,e]}function k(r){if(r.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${r.join(", ")}`);return{flags:r}}var g=class r{constructor(e,t){this.packetId=e;this.entries=t?O(t):[];let i=x(this.entries);this.minimumByteLength=i.minimumByteLength,this.canFastWrite=i.canFastWrite}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new r(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return r.visit(e,I,t)}static visitDataView(e,...t){return r.visit(e,d,t)}static visitArrayBuffer(e,t,i,...n){return r.visit(new DataView(e,t,i),d,n)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,I)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,d)}readArrayBuffer(e,t,i){return this.read(F?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,F?I:d)}writeNodeBuffer(e){let t=Buffer.allocUnsafe(this.minimumByteLength);return this.write(t,e,{offset:0},_,h)}writeDataView(e){let t=new DataView(new ArrayBuffer(this.minimumByteLength));return this.write(t,e,{offset:0},m,E)}writeArrayBuffer(e){let t=F?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;canFastWrite;minimumByteLength;static visit(e,t,i){for(let[n,f]of i)if(n.packetId===t[0](e,0))return f(n.read(e,{offset:0},e.byteLength,t))}read(e,t,i,n){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(n[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let f={};for(let[o,T]of this.entries)if(Array.isArray(T)){let s=T[1]??n[0](e,t.offset++),a=Array(s),l=T[0];if(typeof l=="object")for(let N=0;N<s;++N)a[N]=l.read(e,t,i,n);else{let N=y[l];for(let u=0;u<s;++u)a[u]=n[l](e,t.offset),t.offset+=N}f[o]=a}else if(typeof T=="number")f[o]=n[T](e,t.offset),t.offset+=y[T];else if("flags"in T){let s=n[0](e,t.offset);t.offset+=1,f[o]={};for(let a=0;a<T.flags.length;++a)f[o][T.flags[a]]=!!(s&1<<a)}else f[o]=T.read(e,t,i,n);return f}write(e,t,i,n,f){return n[0](e,this.packetId,i.offset),i.offset+=1,this.canFastWrite?(this.fastWrite(e,t,i,n),e):this.slowWrite(e,t,i,this.minimumByteLength,this.minimumByteLength,n,f)}fastWrite(e,t,i,n){for(let[f,o]of this.entries){let T=t[f];if(Array.isArray(o)){let s=o[0],a=o[1];if(typeof s=="object")for(let l=0;l<a;++l)s.fastWrite(e,T[l],i,n);else{let l=y[s];for(let N=0;N<a;++N)n[s](e,T[N],i.offset),i.offset+=l}}else if(typeof o=="number")n[o](e,T,i.offset),i.offset+=y[o];else if("flags"in o){let s=0;for(let a=0;a<o.flags.length;++a)T[o.flags[a]]&&(s|=1<<a);n[0](e,s,i.offset),i.offset+=1}else o.fastWrite(e,T,i,n)}}slowWrite(e,t,i,n,f,o,T){for(let[s,a]of this.entries){let l=t[s];if(Array.isArray(a)){let N=l.length,u=a[1]===void 0;if(u&&(o[0](e,N,i.offset),i.offset+=1),N>0){let B=a[0];if(typeof B=="object"){if(u){let c=N*B.minimumByteLength;n+=c,f+=c,e.byteLength<f&&(e=T(e,f))}for(let c of l)o[0](e,B.packetId,i.offset),i.offset+=1,e=B.slowWrite(e,c,i,n,f,o,T),n=i.offset,f=e.byteLength}else{let c=y[B];if(u){let p=N*c;n+=p,f+=p,e.byteLength<f&&(e=T(e,f))}for(let p of l)o[B](e,p,i.offset),i.offset+=c}}}else if(typeof a=="number")o[a](e,l,i.offset),i.offset+=y[a];else if("flags"in a){let N=0;for(let u=0;u<a.flags.length;++u)l[a.flags[u]]&&(N|=1<<u);o[0](e,N,i.offset),i.offset+=1}else o[0](e,a.packetId,i.offset),i.offset+=1,e=a.slowWrite(e,l,i,n,f,o,T),n=i.offset,f=e.byteLength}return e}};function O(r){return Object.entries(r).sort(([e],[t])=>e.localeCompare(t))}function x(r){let e=1,t=!0;for(let[,i]of r)if(Array.isArray(i))if(i.length===2){let n=typeof i[0]=="object"?i[0].minimumByteLength:y[i[0]];e+=i[1]*n}else e+=1,t=!1;else i instanceof g?(e+=i.minimumByteLength,t&&=i.canFastWrite):typeof i=="object"?e+=1:e+=y[i];return{minimumByteLength:e,canFastWrite:t}}var y=Array(8);y[0]=1;y[3]=1;y[1]=2;y[4]=2;y[2]=4;y[5]=4;y[6]=4;y[7]=8;var d=Array(8);d[0]=(r,e)=>r.getUint8(e);d[3]=(r,e)=>r.getInt8(e);d[1]=(r,e)=>r.getUint16(e);d[4]=(r,e)=>r.getInt16(e);d[2]=(r,e)=>r.getUint32(e);d[5]=(r,e)=>r.getInt32(e);d[6]=(r,e)=>r.getFloat32(e);d[7]=(r,e)=>r.getFloat64(e);var m=Array(8);m[0]=(r,e,t)=>r.setUint8(t,e);m[3]=(r,e,t)=>r.setInt8(t,e);m[1]=(r,e,t)=>r.setUint16(t,e);m[4]=(r,e,t)=>r.setInt16(t,e);m[2]=(r,e,t)=>r.setUint32(t,e);m[5]=(r,e,t)=>r.setInt32(t,e);m[6]=(r,e,t)=>r.setFloat32(t,e);m[7]=(r,e,t)=>r.setFloat64(t,e);var _=Array(8);F&&(_[0]=(r,e,t)=>r.writeUint8(e,t),_[3]=(r,e,t)=>r.writeInt8(e,t),_[1]=(r,e,t)=>r.writeUint16LE(e,t),_[4]=(r,e,t)=>r.writeInt16LE(e,t),_[2]=(r,e,t)=>r.writeUint32LE(e,t),_[5]=(r,e,t)=>r.writeInt32LE(e,t),_[6]=(r,e,t)=>r.writeFloatLE(e,t),_[7]=(r,e,t)=>r.writeDoubleLE(e,t));var I=Array(8);F&&(I[0]=(r,e)=>r.readUint8(e),I[3]=(r,e)=>r.readInt8(e),I[1]=(r,e)=>r.readUint16LE(e),I[4]=(r,e)=>r.readInt16LE(e),I[2]=(r,e)=>r.readUint32LE(e),I[5]=(r,e)=>r.readInt32LE(e),I[6]=(r,e)=>r.readFloatLE(e),I[7]=(r,e)=>r.readDoubleLE(e));0&&(module.exports={BinaryPacket,Field,FieldArray,FieldBitFlags,FieldFixedArray});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/buffers.ts"],"sourcesContent":["import { growDataView, growNodeBuffer, hasNodeBuffers } from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\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 === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n 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 const data = dataOut[name]\r\n\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\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(\r\n buffer,\r\n (data as any[])[i] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\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 as number[])[i], offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, data as ToJson<Definition>, offsetPointer, writeFunctions)\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 === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n 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 }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\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 : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\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 if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, 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":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,UAAAC,EAAA,eAAAC,EAAA,kBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCAO,IAAMQ,EAAiB,OAAO,QAAW,WAEzC,SAASC,EAAaC,EAAoBC,EAAuB,CACtE,IAAMC,EAAgB,IAAI,YAAYD,CAAa,EAC7CE,EAAe,KAAK,IAAIH,EAAS,WAAYE,EAAc,UAAU,EAGvEE,EAAS,KAAK,MAAMD,EAAe,CAAC,EACxC,IAAI,aAAaD,EAAe,EAAGE,CAAM,EAAE,IAAI,IAAI,aAAaJ,EAAS,OAAQ,EAAGI,CAAM,CAAC,EAG3F,IAAMC,EAASD,EAAS,EACxB,OAAAA,EAASD,EAAeE,EACxB,IAAI,WAAWH,EAAeG,EAAQD,CAAM,EAAE,IAAI,IAAI,WAAWJ,EAAS,OAAQK,EAAQD,CAAM,CAAC,EAE1F,IAAI,SAASF,CAAa,CACnC,CAEO,SAASI,EAAeC,EAAgBN,EAAuB,CACpE,IAAMO,EAAY,OAAO,YAAYP,CAAa,EAClD,OAAAM,EAAO,KAAKC,CAAS,EACdA,CACT,CDpBO,IAAWC,OAKhBA,IAAA,eAAiB,GAAjB,iBAMAA,IAAA,qCAMAA,IAAA,qCAMAA,IAAA,iBAMAA,IAAA,mBAMAA,IAAA,mBAKAA,IAAA,uBAKAA,IAAA,uBA7CgBA,OAAA,IAwDX,SAASC,EAAuDC,EAAwB,C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M,EAE5ElC,EAAiB,CAAc,EAAI,CAACiC,EAAMC,IAAWD,EAAK,aAAaC,CAAM","names":["src_exports","__export","BinaryPacket","Field","FieldArray","FieldBitFlags","FieldFixedArray","__toCommonJS","hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","dataIn","offsetPointer","byteLength","GET_FUNCTION_BUF","GET_FUNCTION","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","readFunctions","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","writeFunctions","growBufferFunction","data","maxByteLength","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","canFastWrite","type","view","offset","value"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/buffers.ts"],"sourcesContent":["import { growDataView, growNodeBuffer, hasNodeBuffers, type TrueArrayBuffer } from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION_BUF)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : new DataView(dataIn, byteOffset, byteLength),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const buffer = Buffer.allocUnsafe(this.minimumByteLength)\r\n 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 /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly 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 static visit(\r\n dataIn: Buffer | DataView,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions))\r\n }\r\n }\r\n }\r\n\r\n private read(\r\n dataIn: DataView | Buffer,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n 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 const data = dataOut[name]\r\n\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\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(\r\n buffer,\r\n (data as any[])[i] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\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 as number[])[i], offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, data as ToJson<Definition>, offsetPointer, writeFunctions)\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 === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n 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 }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n 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 if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, 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","/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,UAAAC,EAAA,eAAAC,EAAA,kBAAAC,EAAA,oBAAAC,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CAACsC,EAAMC,IAAWD,EAAK,aAAaC,CAAM,EACpFvC,EAAiB,CAAY,EAAI,CAACsC,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAC1EvC,EAAiB,CAAc,EAAI,CAACsC,EAAMC,IAAWD,EAAK,YAAYC,CAAM,EAE5EvC,EAAiB,CAAc,EAAI,CAACsC,EAAMC,IAAWD,EAAK,aAAaC,CAAM","names":["src_exports","__export","BinaryPacket","Field","FieldArray","FieldBitFlags","FieldFixedArray","__toCommonJS","hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","GET_FUNCTION","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","onVisit","readFunctions","Packet","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","writeFunctions","growBufferFunction","data","maxByteLength","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","canFastWrite","type","view","offset","value"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=typeof Buffer=="function";function D(r,e){let t=new ArrayBuffer(e),i=Math.min(r.byteLength,t.byteLength),n=Math.trunc(i/8);new Float64Array(t,0,n).set(new Float64Array(r.buffer,0,n));let f=n*8;return n=i-f,new Uint8Array(t,f,n).set(new Uint8Array(r.buffer,f,n)),new DataView(t)}function E(r,e){let t=Buffer.allocUnsafe(e);return r.copy(t),t}var h=(s=>(s[s.UNSIGNED_INT_8=0]="UNSIGNED_INT_8",s[s.UNSIGNED_INT_16=1]="UNSIGNED_INT_16",s[s.UNSIGNED_INT_32=2]="UNSIGNED_INT_32",s[s.INT_8=3]="INT_8",s[s.INT_16=4]="INT_16",s[s.INT_32=5]="INT_32",s[s.FLOAT_32=6]="FLOAT_32",s[s.FLOAT_64=7]="FLOAT_64",s))(h||{});function S(r){return[r]}function L(r,e){if(e<0||!Number.isFinite(e))throw new RangeError("Length of a FixedArray must be a positive integer.");return[r,e]}function G(r){if(r.length>8)throw new Error(`Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${r.join(", ")}`);return{flags:r}}var g=class r{constructor(e,t){this.packetId=e;this.entries=t?U(t):[];let i=w(this.entries);this.minimumByteLength=i.minimumByteLength,this.canFastWrite=i.canFastWrite}static define(e,t){if(e<0||!Number.isFinite(e))throw new RangeError("Packet IDs must be positive integers.");if(e>255)throw new RangeError("Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?");return new r(e,t)}static readPacketIdNodeBuffer(e,t=0){return e.readUint8(t)}static readPacketIdDataView(e,t=0){return e.getUint8(t)}static readPacketIdArrayBuffer(e,t){return new Uint8Array(e,t,1)[0]}static visitNodeBuffer(e,...t){return r.visit(e,I,t)}static visitDataView(e,...t){return r.visit(e,d,t)}static visitArrayBuffer(e,t,i,...n){return r.visit(new DataView(e,t,i),d,n)}readNodeBuffer(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,I)}readDataView(e,t={offset:0},i=e.byteLength){return this.read(e,t,i,d)}readArrayBuffer(e,t,i){return this.read(F?Buffer.from(e,t,i):new DataView(e,t,i),{offset:0},i,F?I:d)}writeNodeBuffer(e){let t=Buffer.allocUnsafe(this.minimumByteLength);return this.write(t,e,{offset:0},_,E)}writeDataView(e){let t=new DataView(new ArrayBuffer(this.minimumByteLength));return this.write(t,e,{offset:0},m,D)}writeArrayBuffer(e){let t=F?this.writeNodeBuffer(e):this.writeDataView(e);return{buffer:t.buffer,byteLength:t.byteLength,byteOffset:t.byteOffset}}visitor(e){return[this,e]}entries;canFastWrite;minimumByteLength;static visit(e,t,i){for(let[n,f]of i)if(n.packetId===t[0](e,0))return f(n.read(e,{offset:0},e.byteLength,t))}read(e,t,i,n){if(i+t.offset<this.minimumByteLength)throw new Error(`There is no space available to fit a packet of type ${this.packetId} at offset ${t.offset}`);if(n[0](e,t.offset)!==this.packetId)throw new Error(`Data at offset ${t.offset} is not a packet of type ${this.packetId}`);t.offset+=1;let f={};for(let[o,T]of this.entries)if(Array.isArray(T)){let s=T[1]??n[0](e,t.offset++),a=Array(s),l=T[0];if(typeof l=="object")for(let N=0;N<s;++N)a[N]=l.read(e,t,i,n);else{let N=y[l];for(let u=0;u<s;++u)a[u]=n[l](e,t.offset),t.offset+=N}f[o]=a}else if(typeof T=="number")f[o]=n[T](e,t.offset),t.offset+=y[T];else if("flags"in T){let s=n[0](e,t.offset);t.offset+=1,f[o]={};for(let a=0;a<T.flags.length;++a)f[o][T.flags[a]]=!!(s&1<<a)}else f[o]=T.read(e,t,i,n);return f}write(e,t,i,n,f){return n[0](e,this.packetId,i.offset),i.offset+=1,this.canFastWrite?(this.fastWrite(e,t,i,n),e):this.slowWrite(e,t,i,this.minimumByteLength,this.minimumByteLength,n,f)}fastWrite(e,t,i,n){for(let[f,o]of this.entries){let T=t[f];if(Array.isArray(o)){let s=o[0],a=o[1];if(typeof s=="object")for(let l=0;l<a;++l)s.fastWrite(e,T[l],i,n);else{let l=y[s];for(let N=0;N<a;++N)n[s](e,T[N],i.offset),i.offset+=l}}else if(typeof o=="number")n[o](e,T,i.offset),i.offset+=y[o];else if("flags"in o){let s=0;for(let a=0;a<o.flags.length;++a)T[o.flags[a]]&&(s|=1<<a);n[0](e,s,i.offset),i.offset+=1}else o.fastWrite(e,T,i,n)}}slowWrite(e,t,i,n,f,o,T){for(let[s,a]of this.entries){let l=t[s];if(Array.isArray(a)){let N=l.length,u=a[1]===void 0;if(u&&(o[0](e,N,i.offset),i.offset+=1),N>0){let B=a[0];if(typeof B=="object"){if(u){let c=N*B.minimumByteLength;n+=c,f+=c,e.byteLength<f&&(e=T(e,f))}for(let c of l)o[0](e,B.packetId,i.offset),i.offset+=1,e=B.slowWrite(e,c,i,n,f,o,T),n=i.offset,f=e.byteLength}else{let c=y[B];if(u){let p=N*c;n+=p,f+=p,e.byteLength<f&&(e=T(e,f))}for(let p of l)o[B](e,p,i.offset),i.offset+=c}}}else if(typeof a=="number")o[a](e,l,i.offset),i.offset+=y[a];else if("flags"in a){let N=0;for(let u=0;u<a.flags.length;++u)l[a.flags[u]]&&(N|=1<<u);o[0](e,N,i.offset),i.offset+=1}else o[0](e,a.packetId,i.offset),i.offset+=1,e=a.slowWrite(e,l,i,n,f,o,T),n=i.offset,f=e.byteLength}return e}};function U(r){return Object.entries(r).sort(([e],[t])=>e.localeCompare(t))}function w(r){let e=1,t=!0;for(let[,i]of r)if(Array.isArray(i))if(i.length===2){let n=typeof i[0]=="object"?i[0].minimumByteLength:y[i[0]];e+=i[1]*n}else e+=1,t=!1;else i instanceof g?(e+=i.minimumByteLength,t&&=i.canFastWrite):typeof i=="object"?e+=1:e+=y[i];return{minimumByteLength:e,canFastWrite:t}}var y=Array(8);y[0]=1;y[3]=1;y[1]=2;y[4]=2;y[2]=4;y[5]=4;y[6]=4;y[7]=8;var d=Array(8);d[0]=(r,e)=>r.getUint8(e);d[3]=(r,e)=>r.getInt8(e);d[1]=(r,e)=>r.getUint16(e);d[4]=(r,e)=>r.getInt16(e);d[2]=(r,e)=>r.getUint32(e);d[5]=(r,e)=>r.getInt32(e);d[6]=(r,e)=>r.getFloat32(e);d[7]=(r,e)=>r.getFloat64(e);var m=Array(8);m[0]=(r,e,t)=>r.setUint8(t,e);m[3]=(r,e,t)=>r.setInt8(t,e);m[1]=(r,e,t)=>r.setUint16(t,e);m[4]=(r,e,t)=>r.setInt16(t,e);m[2]=(r,e,t)=>r.setUint32(t,e);m[5]=(r,e,t)=>r.setInt32(t,e);m[6]=(r,e,t)=>r.setFloat32(t,e);m[7]=(r,e,t)=>r.setFloat64(t,e);var _=Array(8);F&&(_[0]=(r,e,t)=>r.writeUint8(e,t),_[3]=(r,e,t)=>r.writeInt8(e,t),_[1]=(r,e,t)=>r.writeUint16LE(e,t),_[4]=(r,e,t)=>r.writeInt16LE(e,t),_[2]=(r,e,t)=>r.writeUint32LE(e,t),_[5]=(r,e,t)=>r.writeInt32LE(e,t),_[6]=(r,e,t)=>r.writeFloatLE(e,t),_[7]=(r,e,t)=>r.writeDoubleLE(e,t));var I=Array(8);F&&(I[0]=(r,e)=>r.readUint8(e),I[3]=(r,e)=>r.readInt8(e),I[1]=(r,e)=>r.readUint16LE(e),I[4]=(r,e)=>r.readInt16LE(e),I[2]=(r,e)=>r.readUint32LE(e),I[5]=(r,e)=>r.readInt32LE(e),I[6]=(r,e)=>r.readFloatLE(e),I[7]=(r,e)=>r.readDoubleLE(e));export{g as BinaryPacket,h as Field,S as FieldArray,G as FieldBitFlags,L as FieldFixedArray};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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 a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\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 === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n 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 const data = dataOut[name]\r\n\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\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(\r\n buffer,\r\n (data as any[])[i] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\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 as number[])[i], offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, data as ToJson<Definition>, offsetPointer, writeFunctions)\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 === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n 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 }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\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 : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\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 if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, 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"],"mappings":"AAAO,IAAMA,EAAiB,OAAO,QAAW,WAEzC,SAASC,EAAaC,EAAoBC,EAAuB,CACtE,IAAMC,EAAgB,IAAI,YAAYD,CAAa,EAC7CE,EAAe,KAAK,IAAIH,EAAS,WAAYE,EAAc,UAAU,EAGvEE,EAAS,KAAK,MAAMD,EAAe,CAAC,EACxC,IAAI,aAAaD,EAAe,EAAGE,CAAM,EAAE,IAAI,IAAI,aAAaJ,EAAS,OAAQ,EAAGI,CAAM,CAAC,EAG3F,IAAMC,EAASD,EAAS,EACxB,OAAAA,EAASD,EAAeE,EACxB,IAAI,WAAWH,EAAeG,EAAQD,CAAM,EAAE,IAAI,IAAI,WAAWJ,EAAS,OAAQK,EAAQD,CAAM,CAAC,EAE1F,IAAI,SAASF,CAAa,CACnC,CAEO,SAASI,EAAeC,EAAgBN,EAAuB,CACpE,IAAMO,EAAY,OAAO,YAAYP,CAAa,EAClD,OAAAM,EAAO,KAAKC,CAAS,EACdA,CACT,CCpBO,IAAWC,OAKhBA,IAAA,eAAiB,GAAjB,iBAMAA,IAAA,qCAMAA,IAAA,qCAMAA,IAAA,iBAMAA,IAAA,mBAMAA,IAAA,mBAKAA,IAAA,uBAKAA,IAAA,uBA7CgBA,OAAA,IAwDX,SAASC,EAAuDC,EAAwB,CAC7F,MAAO,CAACA,CAAI,CACd,CASO,SAASC,EACdD,EACAE,EAC+B,CA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AaC,CAAM","names":["hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","dataIn","offsetPointer","byteLength","GET_FUNCTION_BUF","GET_FUNCTION","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","readFunctions","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","writeFunctions","growBufferFunction","data","maxByteLength","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","canFastWrite","type","view","offset","value"]}
|
|
1
|
+
{"version":3,"sources":["../src/buffers.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Exclusively matches objects of type `ArrayBuffer` and no other types that inherit from it. \\\r\n * This is needed because the `DataView` constructor explicitly requires a \"true\" ArrayBuffer, or else it throws.\r\n */\r\nexport type TrueArrayBuffer = ArrayBuffer & { buffer?: undefined }\r\n\r\nexport const hasNodeBuffers = typeof Buffer === 'function'\r\n\r\nexport function growDataView(dataview: DataView, newByteLength: number) {\r\n const resizedBuffer = new ArrayBuffer(newByteLength)\r\n const amountToCopy = Math.min(dataview.byteLength, resizedBuffer.byteLength)\r\n\r\n // Treat the buffer as if it was a Float64Array so we can copy 8 bytes at a time, to finish faster\r\n let length = Math.trunc(amountToCopy / 8)\r\n new Float64Array(resizedBuffer, 0, length).set(new Float64Array(dataview.buffer, 0, length))\r\n\r\n // Copy the remaining up to 7 bytes\r\n const offset = length * 8\r\n length = amountToCopy - offset\r\n new Uint8Array(resizedBuffer, offset, length).set(new Uint8Array(dataview.buffer, offset, length))\r\n\r\n return new DataView(resizedBuffer)\r\n}\r\n\r\nexport function growNodeBuffer(buffer: Buffer, newByteLength: number) {\r\n const newBuffer = Buffer.allocUnsafe(newByteLength)\r\n buffer.copy(newBuffer)\r\n return newBuffer\r\n}\r\n","import { growDataView, growNodeBuffer, hasNodeBuffers, type TrueArrayBuffer } from './buffers'\r\n\r\nexport const enum Field {\r\n /**\r\n * Defines a 1 byte (8 bits) unsigned integer field. \\\r\n * (Range: 0 - 255)\r\n */\r\n UNSIGNED_INT_8 = 0,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) unsigned integer field. \\\r\n * (Range: 0 - 65535)\r\n */\r\n UNSIGNED_INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) unsigned integer field. \\\r\n * (Range: 0 - 4294967295)\r\n */\r\n UNSIGNED_INT_32,\r\n\r\n /**\r\n * Defines a 1 byte (8 bits) signed integer field. \\\r\n * (Range: -128 - 127)\r\n */\r\n INT_8,\r\n\r\n /**\r\n * Defines a 2 bytes (16 bits) signed integer field. \\\r\n * (Range: -32768 - 32767)\r\n */\r\n INT_16,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) signed integer field. \\\r\n * (Range: -2147483648 - 2147483647)\r\n */\r\n INT_32,\r\n\r\n /**\r\n * Defines a 4 bytes (32 bits) floating-point field. \\\r\n */\r\n FLOAT_32,\r\n\r\n /**\r\n * Defines a 8 bytes (64 bits) floating-point field. \\\r\n */\r\n FLOAT_64\r\n}\r\n\r\n/**\r\n * Defines a dynamically-sized array with elements of a certain type. \\\r\n * Dynamically-sized arrays are useful when a packet's field is an array of a non pre-defined length. \\\r\n * Although, this makes dynamically-sized arrays more memory expensive as the internal buffer needs to be grown accordingly.\r\n *\r\n * NOTE: If an array will ALWAYS have the same length, prefer using the `FieldFixedArray` type, for both better performance and memory efficiency. \\\r\n * NOTE: As of now, dynamic arrays can have at most 256 elements.\r\n */\r\nexport function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): [itemType: T] {\r\n return [item]\r\n}\r\n\r\n/**\r\n * Defines a statically-sized array with elements of a certain type. \\\r\n * Fixed arrays are useful when a packet's field is an array of a pre-defined length. \\\r\n * Fixed arrays much more memory efficient and performant than non-fixed ones.\r\n *\r\n * NOTE: If an array will not always have the same length, use the `FieldArray` type.\r\n */\r\nexport function FieldFixedArray<T extends Field | BinaryPacket<Definition>, Length extends number>(\r\n item: T,\r\n length: Length\r\n): [itemType: T, length: Length] {\r\n if (length < 0 || !Number.isFinite(length)) {\r\n throw new RangeError('Length of a FixedArray must be a positive integer.')\r\n }\r\n\r\n return [item, length]\r\n}\r\n\r\ntype BitFlags = (string[] | ReadonlyArray<string>) & {\r\n length: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8\r\n}\r\n\r\n/**\r\n * Defines a sequence of up to 8 \"flags\" (basically single bits/booleans) that can be packed together into a single 8 bits value. \\\r\n * This is useful for minimizing bytes usage when there are lots of boolean fields/flags, instead of saving each flag separately as its own 8 bits value.\r\n *\r\n * The input should be an array of strings (with at most 8 elements) where each string defines the name of a flag. \\\r\n * This is just for definition purposes, then when actually writing or reading packets it'll just be a record-object with those names as keys and boolean values.\r\n */\r\nexport function FieldBitFlags<const FlagsArray extends BitFlags>(flags: FlagsArray) {\r\n if (flags.length > 8) {\r\n throw new Error(\r\n `Invalid BinaryPacket definition: a BitFlags field can have only up to 8 flags, given: ${flags.join(', ')}`\r\n )\r\n }\r\n\r\n return { flags }\r\n}\r\n\r\n/**\r\n * Do not manually construct this type: an object of this kind is returned by a BinaryPacket `createVisitor` method. \\\r\n * Used in the `BinaryPacket::visit` static method to perform a sort of \"pattern matching\" on an incoming packet (of yet unknown type) buffer.\r\n */\r\ntype Visitor = [BinaryPacket<Definition>, (packet: any) => void]\r\n\r\nexport class BinaryPacket<T extends Definition> {\r\n /**\r\n * Defines a new binary packet. \\\r\n * Make sure that every `packetId` is unique.\r\n * @throws RangeError If packetId is negative, floating-point, or greater than 255.\r\n */\r\n static define<T extends Definition>(packetId: number, definition?: T) {\r\n if (packetId < 0 || !Number.isFinite(packetId)) {\r\n throw new RangeError('Packet IDs must be positive integers.')\r\n }\r\n\r\n if (packetId > 255) {\r\n throw new RangeError(\r\n 'Packet IDs greater than 255 are not supported. Do you REALLY need more than 255 different kinds of packets?'\r\n )\r\n }\r\n\r\n return new BinaryPacket(packetId, definition)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given Buffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdNodeBuffer(buffer: Buffer, byteOffset = 0) {\r\n return buffer.readUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given DataView. \\\r\n * This method practically just reads the uint8 at offset `byteOffset` (default: 0). \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n */\r\n static readPacketIdDataView(dataview: DataView, byteOffset = 0) {\r\n return dataview.getUint8(byteOffset)\r\n }\r\n\r\n /**\r\n * Reads just the packetId from the given ArrayBuffer. \\\r\n * This method practically just reads the uint8 at offset `byteOffset`. \\\r\n * Useful if the receiving side receives multiple types of packets.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` argument cannot be defaulted and must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation.\r\n */\r\n static readPacketIdArrayBuffer(arraybuffer: TrueArrayBuffer, byteOffset: number) {\r\n return new Uint8Array(arraybuffer, byteOffset, 1)[0]\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given Buffer through the given visitors. \\\r\n * The Buffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitNodeBuffer(buffer: Buffer, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(buffer, GET_FUNCTION_BUF, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given DataView through the given visitors. \\\r\n * The DataView is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitDataView(dataview: DataView, ...visitors: Visitor[]) {\r\n return BinaryPacket.visit(dataview, GET_FUNCTION, visitors)\r\n }\r\n\r\n /**\r\n * Visits and \"pattern matches\" the given ArrayBuffer through the given visitors. \\\r\n * The ArrayBuffer is compared to the series of visitors through its Packet ID, and, if an appropriate visitor is found: its callback is called.\r\n *\r\n * NOTE: Due to security issues, the `byteOffset` and `byteLength` arguments must be provided by the user. \\\r\n * NOTE: For more information read the `readArrayBuffer` method documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n static visitArrayBuffer(\r\n arraybuffer: TrueArrayBuffer,\r\n byteOffset: number,\r\n byteLength: number,\r\n ...visitors: Visitor[]\r\n ) {\r\n return BinaryPacket.visit(\r\n new DataView(arraybuffer, byteOffset, byteLength),\r\n GET_FUNCTION,\r\n visitors\r\n )\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer reading using this method, as it is much faster than the other ones.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readNodeBuffer(\r\n dataIn: Buffer,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION_BUF)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given DataView.\r\n *\r\n * NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \\\r\n * NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.\r\n */\r\n readDataView(\r\n dataIn: DataView,\r\n offsetPointer = { offset: 0 },\r\n byteLength = dataIn.byteLength\r\n ): ToJson<T> {\r\n return this.read(dataIn, offsetPointer, byteLength, GET_FUNCTION)\r\n }\r\n\r\n /**\r\n * Reads/deserializes from the given ArrayBuffer. \\\r\n * WARNING: this method is practically a HACK.\r\n *\r\n * When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \\\r\n * This is to prevent serious bugs and security issues. \\\r\n * That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.\r\n *\r\n * NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \\\r\n * NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.\r\n */\r\n readArrayBuffer(dataIn: TrueArrayBuffer, byteOffset: number, byteLength: number) {\r\n return this.read(\r\n hasNodeBuffers\r\n ? Buffer.from(dataIn, byteOffset, byteLength)\r\n : new DataView(dataIn, byteOffset, byteLength),\r\n { offset: 0 }, // The underlying buffer has already been offsetted\r\n byteLength,\r\n hasNodeBuffers ? GET_FUNCTION_BUF : GET_FUNCTION\r\n )\r\n }\r\n\r\n /**\r\n * Writes/serializes the given object into a Buffer. \\\r\n * Method available ONLY on NodeJS and Bun.\r\n *\r\n * If possible, always prefer writing using this method, as it is much faster than the other ones.\r\n */\r\n writeNodeBuffer(dataOut: ToJson<T>) {\r\n const buffer = Buffer.allocUnsafe(this.minimumByteLength)\r\n 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 /**\r\n * Creates a \"visitor\" object for this BinaryPacket definition. \\\r\n * Used when visiting and \"pattern matching\" buffers with the `BinaryPacket::visit` static utility methods. \\\r\n *\r\n * For more information read the `BinaryPacket::visitNodeBuffer` documentation. \\\r\n * NOTE: If visiting packets in a loop, for both performance and memory efficiency reasons, it is much better to create each visitor only once before the loop starts and not every iteration.\r\n */\r\n visitor(onVisit: (packet: ToJson<T>) => void): Visitor {\r\n return [this, onVisit]\r\n }\r\n\r\n /// PRIVATE\r\n\r\n private readonly entries: Entries\r\n readonly 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 static visit(\r\n dataIn: Buffer | DataView,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF,\r\n visitors: Visitor[]\r\n ) {\r\n for (const [Packet, onVisit] of visitors) {\r\n if (Packet.packetId === readFunctions[Field.UNSIGNED_INT_8](dataIn as any, 0)) {\r\n return onVisit(Packet.read(dataIn, { offset: 0 }, dataIn.byteLength, readFunctions))\r\n }\r\n }\r\n }\r\n\r\n private read(\r\n dataIn: DataView | Buffer,\r\n offsetPointer: { offset: number },\r\n byteLength: number,\r\n readFunctions: typeof GET_FUNCTION | typeof GET_FUNCTION_BUF\r\n ): ToJson<T> {\r\n if (byteLength + offsetPointer.offset < this.minimumByteLength) {\r\n throw new Error(\r\n `There is no space available to fit a packet of type ${this.packetId} at offset ${offsetPointer.offset}`\r\n )\r\n }\r\n\r\n if (\r\n readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset) !== this.packetId\r\n ) {\r\n throw new Error(\r\n `Data at offset ${offsetPointer.offset} is not a packet of type ${this.packetId}`\r\n )\r\n }\r\n\r\n offsetPointer.offset += 1\r\n const result: any = {}\r\n\r\n for (const [name, def] of this.entries) {\r\n if (Array.isArray(def)) {\r\n const length =\r\n // def[1] is the length of a statically-sized array, if undefined: must read the length from the buffer as it means it's a dynamically-sized array\r\n def[1] ?? readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset++)\r\n\r\n const array = Array(length)\r\n\r\n const itemType = def[0]\r\n\r\n if (typeof itemType === 'object') {\r\n // Array of \"subpackets\"\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = itemType.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n } else {\r\n // Array of primitives (numbers)\r\n const itemSize = BYTE_SIZE[itemType]\r\n\r\n // It seems like looping over each element is actually much faster than using TypedArrays bulk copy.\r\n // TODO: properly benchmark with various array sizes to see if it's actually the case.\r\n for (let i = 0; i < length; ++i) {\r\n array[i] = readFunctions[itemType](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = array\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = readFunctions[def](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n const flags = readFunctions[Field.UNSIGNED_INT_8](dataIn as any, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = {}\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name][def.flags[bit]] = !!(flags & (1 << bit))\r\n }\r\n } else {\r\n // Single \"subpacket\"\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n result[name] = def.read(dataIn, offsetPointer, byteLength, readFunctions)\r\n }\r\n }\r\n\r\n return result as ToJson<T>\r\n }\r\n\r\n private write<Buf extends DataView | Buffer>(\r\n buffer: Buf,\r\n dataOut: ToJson<T>,\r\n offsetPointer: { offset: number },\r\n 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 const data = dataOut[name]\r\n\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\r\n if (typeof itemType === 'object') {\r\n for (let i = 0; i < length; ++i) {\r\n itemType.fastWrite(\r\n buffer,\r\n (data as any[])[i] as ToJson<Definition>,\r\n offsetPointer,\r\n writeFunctions\r\n )\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 as number[])[i], offsetPointer.offset)\r\n offsetPointer.offset += itemSize\r\n }\r\n }\r\n } else if (typeof def === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n // In fastWrite there cannot be arrays, but the cast is needed because TypeScript can't possibly know that.\r\n def.fastWrite(buffer, data as ToJson<Definition>, offsetPointer, writeFunctions)\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 === 'number') {\r\n // Single primitive (number)\r\n writeFunctions[def](buffer as any, data as number, offsetPointer.offset)\r\n offsetPointer.offset += BYTE_SIZE[def]\r\n } else if ('flags' in def) {\r\n // BitFlags\r\n let flags = 0\r\n\r\n for (let bit = 0; bit < def.flags.length; ++bit) {\r\n if ((data as Record<string, boolean>)[def.flags[bit]]) {\r\n flags |= 1 << bit\r\n }\r\n }\r\n\r\n writeFunctions[Field.UNSIGNED_INT_8](buffer as any, flags, offsetPointer.offset)\r\n offsetPointer.offset += 1\r\n } else {\r\n // Single \"subpacket\"\r\n 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 }\r\n }\r\n\r\n return buffer\r\n }\r\n}\r\n\r\n/**\r\n * BinaryPacket definition: \\\r\n * Any packet can be defined through a \"schema\" object explaining its fields names and types.\r\n *\r\n * @example\r\n * // Imagine we have a game board where each cell is a square and is one unit big.\r\n * // A cell can be then defined by its X and Y coordinates.\r\n * // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.\r\n * const Cell = {\r\n * x: Field.UNSIGNED_INT_8,\r\n * y: Field.UNSIGNED_INT_8\r\n * }\r\n *\r\n * // When done with the cell definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const CellPacket = BinaryPacket.define(0, Cell)\r\n *\r\n * // Let's now make the definition of the whole game board.\r\n * // You can also specify arrays of both \"primitive\" fields and other BinaryPackets.\r\n * const Board = {\r\n * numPlayers: Field.UNSIGNED_INT_8,\r\n * cells: FieldArray(CellPacket)\r\n * }\r\n *\r\n * // When done with the board definition we can create its BinaryPacket writer/reader.\r\n * // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.\r\n * const BoardPacket = BinaryPacket.define(1, Board)\r\n *\r\n * // And use it.\r\n * const buffer = BoardPacket.writeNodeBuffer({\r\n * numPlayers: 1,\r\n * cells: [\r\n * { x: 0, y: 0 },\r\n * { x: 1, y: 1 }\r\n * ]\r\n * })\r\n *\r\n * // sendTheBufferOver(buffer)\r\n * // ...\r\n * // const buffer = receiveTheBuffer()\r\n * const board = BoardPacket.readNodeBuffer(buffer)\r\n * // ...\r\n */\r\nexport type Definition = {\r\n [fieldName: string]:\r\n | MaybeArray<Field>\r\n | MaybeArray<BinaryPacket<Definition>>\r\n | { flags: BitFlags }\r\n}\r\n\r\ntype MaybeArray<T> = T | [itemType: T] | [itemType: T, length: number]\r\n\r\ntype BitFlagsToJson<FlagsArray extends BitFlags> = {\r\n [key in FlagsArray[number]]: boolean\r\n}\r\n\r\n/**\r\n * Meta-type that converts a `Definition` schema to the type of the actual JavaScript object that will be written into a packet or read from. \\\r\n */\r\nexport type ToJson<T extends Definition> = {\r\n [K in keyof T]: T[K] extends [infer Item]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[]\r\n : number[]\r\n : T[K] extends [infer Item, infer Length]\r\n ? Item extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>[] & { length: Length }\r\n : number[] & { length: Length }\r\n : T[K] extends BinaryPacket<infer BPDef>\r\n ? ToJson<BPDef>\r\n : T[K] extends { flags: infer FlagsArray extends BitFlags }\r\n ? BitFlagsToJson<FlagsArray>\r\n : number\r\n}\r\n\r\n/**\r\n * In a JavaScript object, the order of its keys is not strictly defined: sort them by field name. \\\r\n * Thus, we cannot trust iterating over an object keys: we MUST iterate over its entries array. \\\r\n * This is important to make sure that whoever shares BinaryPacket definitions can correctly write/read packets independently of their JS engines.\r\n */\r\nfunction sortEntries(definition: Definition) {\r\n return Object.entries(definition).sort(([fieldName1], [fieldName2]) =>\r\n fieldName1.localeCompare(fieldName2)\r\n )\r\n}\r\n\r\ntype Entries = ReturnType<typeof sortEntries>\r\n\r\n/**\r\n * Helper function that \"inspects\" the entries of a BinaryPacket definition\r\n * and returns useful \"stats\" needed for writing and reading buffers.\r\n *\r\n * This function is ever called only once per BinaryPacket definition.\r\n */\r\nfunction inspectEntries(entries: Entries) {\r\n // The PacketID is already 1 byte, that's why we aren't starting from 0.\r\n let minimumByteLength = 1\r\n 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 if (typeof type === 'object') {\r\n // BitFlags\r\n // BitFlags are always 1 byte long, because they can hold up to 8 booleans\r\n minimumByteLength += 1\r\n } else {\r\n minimumByteLength += BYTE_SIZE[type]\r\n }\r\n }\r\n\r\n return { minimumByteLength, 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"],"mappings":"AAMO,IAAMA,EAAiB,OAAO,QAAW,WAEzC,SAASC,EAAaC,EAAoBC,EAAuB,CACtE,IAAMC,EAAgB,IAAI,YAAYD,CAAa,EAC7CE,EAAe,KAAK,IAAIH,EAAS,WAAYE,EAAc,UAAU,EAGvEE,EAAS,KAAK,MAAMD,EAAe,CAAC,EACxC,IAAI,aAAaD,EAAe,E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names":["hasNodeBuffers","growDataView","dataview","newByteLength","resizedBuffer","amountToCopy","length","offset","growNodeBuffer","buffer","newBuffer","Field","FieldArray","item","FieldFixedArray","length","FieldBitFlags","flags","BinaryPacket","_BinaryPacket","packetId","definition","sortEntries","inspection","inspectEntries","buffer","byteOffset","dataview","arraybuffer","visitors","GET_FUNCTION_BUF","GET_FUNCTION","byteLength","dataIn","offsetPointer","hasNodeBuffers","dataOut","SET_FUNCTION_BUF","growNodeBuffer","SET_FUNCTION","growDataView","buf","onVisit","readFunctions","Packet","result","name","def","array","itemType","i","itemSize","BYTE_SIZE","bit","writeFunctions","growBufferFunction","data","maxByteLength","isDynamicArray","neededBytesForElements","object","number","fieldName1","fieldName2","entries","minimumByteLength","canFastWrite","type","view","offset","value"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "binary-packet",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
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",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
],
|
|
11
11
|
"scripts": {
|
|
12
12
|
"build": "tsup",
|
|
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",
|
|
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 && node -r ts-node/register/transpile-only src/tests/visitors.test.ts",
|
|
14
14
|
"benchmark": "node -r ts-node/register/transpile-only src/tests/benchmark.test.ts",
|
|
15
15
|
"lint": "eslint"
|
|
16
16
|
},
|