binary-packet 1.0.0
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/LICENSE +61 -0
- package/README.md +125 -0
- package/dist/index.d.mts +181 -0
- package/dist/index.d.ts +181 -0
- package/dist/index.js +385 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +356 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Apache License, Version 2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
|
|
2
|
+
|
|
3
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
4
|
+
|
|
5
|
+
1. Definitions.
|
|
6
|
+
|
|
7
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
8
|
+
|
|
9
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
10
|
+
|
|
11
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
12
|
+
|
|
13
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
14
|
+
|
|
15
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
16
|
+
|
|
17
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
18
|
+
|
|
19
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
20
|
+
|
|
21
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
22
|
+
|
|
23
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
24
|
+
|
|
25
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
26
|
+
|
|
27
|
+
2. Grant of Copyright License.
|
|
28
|
+
|
|
29
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License.
|
|
32
|
+
|
|
33
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution.
|
|
36
|
+
|
|
37
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
38
|
+
|
|
39
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
40
|
+
|
|
41
|
+
5. Submission of Contributions.
|
|
42
|
+
|
|
43
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
44
|
+
|
|
45
|
+
6. Trademarks.
|
|
46
|
+
|
|
47
|
+
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty.
|
|
50
|
+
|
|
51
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
52
|
+
|
|
53
|
+
8. Limitation of Liability.
|
|
54
|
+
|
|
55
|
+
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
56
|
+
|
|
57
|
+
9. Accepting Warranty or Additional Liability.
|
|
58
|
+
|
|
59
|
+
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
60
|
+
|
|
61
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# binary-packet
|
|
2
|
+
|
|
3
|
+
Lightweight and hyper-fast, zero-dependencies, TypeScript-first, schema-based binary packets serialization and deserialization library. \
|
|
4
|
+
Originally made to be used for an ultrafast WebSockets communication with user-defined type-safe messages between client and server, with the smallest bytes usage possible.
|
|
5
|
+
|
|
6
|
+
Supports serializing into and deserializing from [**DataView**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)s, [**ArrayBuffer**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)s and [**Buffer**](https://nodejs.org/api/buffer.html#buffer)s (NodeJS/Bun only). \
|
|
7
|
+
To achieve the maximum performance is it always advised to use node Buffer(s) when available.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
Node: \
|
|
12
|
+
`npm install binary-packet`
|
|
13
|
+
|
|
14
|
+
Bun: \
|
|
15
|
+
`bun add binary-packet`
|
|
16
|
+
|
|
17
|
+
## Features & Specification
|
|
18
|
+
|
|
19
|
+
Define the structure of the packets through unique Packet IDs and "schema" objects. \
|
|
20
|
+
This "schema" object is simply called `Definition` and defines the shape of a packet: specifically its `fields` and their `types`.
|
|
21
|
+
|
|
22
|
+
Currently, these kinds of `fields` are supported:
|
|
23
|
+
| Type | Description | Values | Size (bytes) |
|
|
24
|
+
|------|-------------|--------------|--------------|
|
|
25
|
+
| `Field.UNSIGNED_INT_8` | 8 bits unsigned integer | 0 - 255 | 1 |
|
|
26
|
+
| `Field.UNSIGNED_INT_16` | 16 bits unsigned integer | 0 - 65535 | 2 |
|
|
27
|
+
| `Field.UNSIGNED_INT_32` | 32 bits unsigned integer | 0 - 4294967295 | 4 |
|
|
28
|
+
| `Field.INT_8` | 8 bits signed integer | -128 - 127 | 1 |
|
|
29
|
+
| `Field.INT_16` | 16 bits signed integer | -32768 - 32767 | 2 |
|
|
30
|
+
| `Field.INT_32` | 32 bits signed integer | -2147483648 - 2147483647 | 4 |
|
|
31
|
+
| `Field.FLOAT_32` | 32 bits IEEE754 floating-point | | 4 |
|
|
32
|
+
| `Field.FLOAT_64` | 64 bits IEEE754 floating-point | | 8 |
|
|
33
|
+
| `BinaryPacket` | BinaryPacket "subpacket" | BinaryPacket | size(BinaryPacket) |
|
|
34
|
+
| `FieldArray` | Array of one of the types above | Up to 256 elements | 1 + length \* size(Field) |
|
|
35
|
+
|
|
36
|
+
As you can see from the table above, both arrays and nested objects ("subpackets") are supported.
|
|
37
|
+
|
|
38
|
+
## Usage Examples
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
import { BinaryPacket, Field, FieldArray } from 'binary-packet'
|
|
42
|
+
|
|
43
|
+
// Imagine we have a game board where each cell is a square and is one unit big.
|
|
44
|
+
// A cell can be then defined by its X and Y coordinates.
|
|
45
|
+
// For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
|
|
46
|
+
const Cell = {
|
|
47
|
+
x: Field.UNSIGNED_INT_8,
|
|
48
|
+
y: Field.UNSIGNED_INT_8
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// When done with the cell definition we can create its BinaryPacket writer/reader.
|
|
52
|
+
// NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
53
|
+
const CellPacket = BinaryPacket.define(0, Cell)
|
|
54
|
+
|
|
55
|
+
// Let's now make the definition of the whole game board.
|
|
56
|
+
// You can also specify arrays of both "primitive" fields and other BinaryPackets.
|
|
57
|
+
const Board = {
|
|
58
|
+
numPlayers: Field.UNSIGNED_INT_8,
|
|
59
|
+
otherStuff: Field.INT_32,
|
|
60
|
+
cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// When done with the board definition we can create its BinaryPacket writer/reader.
|
|
64
|
+
// NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
65
|
+
const BoardPacket = BinaryPacket.define(1, Board)
|
|
66
|
+
|
|
67
|
+
//////////////////
|
|
68
|
+
// WRITING SIDE //
|
|
69
|
+
//////////////////
|
|
70
|
+
const buffer = BoardPacket.writeNodeBuffer({
|
|
71
|
+
numPlayers: 1,
|
|
72
|
+
otherStuff: 69420,
|
|
73
|
+
cells: [
|
|
74
|
+
{ x: 0, y: 0 },
|
|
75
|
+
{ x: 1, y: 1 }
|
|
76
|
+
]
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
// ...
|
|
80
|
+
// sendTheBufferOverTheNetwork(buffer)
|
|
81
|
+
// ...
|
|
82
|
+
|
|
83
|
+
//////////////////
|
|
84
|
+
// READING SIDE //
|
|
85
|
+
//////////////////
|
|
86
|
+
import assert from 'assert'
|
|
87
|
+
|
|
88
|
+
// ...
|
|
89
|
+
// const buffer = receiveTheBufferFromTheNetwork()
|
|
90
|
+
// ...
|
|
91
|
+
|
|
92
|
+
const board = BoardPacket.readNodeBuffer(buffer)
|
|
93
|
+
|
|
94
|
+
assert(board.numPlayers === 1)
|
|
95
|
+
assert(board.otherStuff === 69420)
|
|
96
|
+
assert(board.cells.length === 2)
|
|
97
|
+
assert(board.cells[0].x === 0)
|
|
98
|
+
assert(board.cells[0].y === 0)
|
|
99
|
+
assert(board.cells[1].x === 1)
|
|
100
|
+
assert(board.cells[1].y === 1)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Benchmarks & Alternatives
|
|
104
|
+
|
|
105
|
+
Benchmarks are not always meant to be taken seriously. \
|
|
106
|
+
Most of the times the results of a benchmark do not actually show the full capabilities of each library. \
|
|
107
|
+
So, take these "performance" comparisons with a grain of salt; or, even better, do your own benchmarks with the actual data you need to serialize/deserialize.
|
|
108
|
+
|
|
109
|
+
This library has been benchmarked against the following alternatives:
|
|
110
|
+
|
|
111
|
+
- [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular and very fast and battle-tested serialization library. It currently offers **many** more features than binary-packet, but it appears to be 2x-4x slower in writes and 3x-10x slower in reads.
|
|
112
|
+
- [restructure](https://www.npmjs.com/package/restructure) - A very popular schema-based serialization library, has some extra features like LazyArrays, but it is **much slower** than both binary-packet and msgpackr. And, sadly, easily crashes with complex structures.
|
|
113
|
+
|
|
114
|
+
The benchmarks are executed on three different kinds of packets:
|
|
115
|
+
|
|
116
|
+
- EmptyPacket: basically an empty javascript object.
|
|
117
|
+
- SimplePacket: objects with primitive-only fields.
|
|
118
|
+
- ComplexPacket: objects with primitives, arrays and other nested objects/arrays.
|
|
119
|
+
|
|
120
|
+
You can see and run the benchmarks yourself if you clone the repository and launch `npm run benchmark`.
|
|
121
|
+
|
|
122
|
+
## Disclaimer
|
|
123
|
+
|
|
124
|
+
This library is still very new, thus not "battle-tested" in production enough.\
|
|
125
|
+
If you plan on serializing highly sensitive data or need to guarantee no crashes, use an alternative like [msgpackr](https://www.npmjs.com/package/msgpackr), or [contribute](https://github.com/silence-cloud-com/binary-packet) to this library yourself!
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
declare const enum Field {
|
|
2
|
+
/**
|
|
3
|
+
* Defines a 1 byte (8 bits) unsigned integer field. \
|
|
4
|
+
* (Range: 0 - 255)
|
|
5
|
+
*/
|
|
6
|
+
UNSIGNED_INT_8 = 0,
|
|
7
|
+
/**
|
|
8
|
+
* Defines a 2 bytes (16 bits) unsigned integer field. \
|
|
9
|
+
* (Range: 0 - 65535)
|
|
10
|
+
*/
|
|
11
|
+
UNSIGNED_INT_16 = 1,
|
|
12
|
+
/**
|
|
13
|
+
* Defines a 4 bytes (32 bits) unsigned integer field. \
|
|
14
|
+
* (Range: 0 - 4294967295)
|
|
15
|
+
*/
|
|
16
|
+
UNSIGNED_INT_32 = 2,
|
|
17
|
+
/**
|
|
18
|
+
* Defines a 1 byte (8 bits) signed integer field. \
|
|
19
|
+
* (Range: -128 - 127)
|
|
20
|
+
*/
|
|
21
|
+
INT_8 = 3,
|
|
22
|
+
/**
|
|
23
|
+
* Defines a 2 bytes (16 bits) signed integer field. \
|
|
24
|
+
* (Range: -32768 - 32767)
|
|
25
|
+
*/
|
|
26
|
+
INT_16 = 4,
|
|
27
|
+
/**
|
|
28
|
+
* Defines a 4 bytes (32 bits) signed integer field. \
|
|
29
|
+
* (Range: -2147483648 - 2147483647)
|
|
30
|
+
*/
|
|
31
|
+
INT_32 = 5,
|
|
32
|
+
/**
|
|
33
|
+
* Defines a 4 bytes (32 bits) floating-point field. \
|
|
34
|
+
*/
|
|
35
|
+
FLOAT_32 = 6,
|
|
36
|
+
/**
|
|
37
|
+
* Defines a 8 bytes (64 bits) floating-point field. \
|
|
38
|
+
*/
|
|
39
|
+
FLOAT_64 = 7
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Defines an array of a certain type. \
|
|
43
|
+
* As of now, only arrays with at most 256 elements are supported.
|
|
44
|
+
*/
|
|
45
|
+
declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): T[];
|
|
46
|
+
declare class BinaryPacket<T extends Definition> {
|
|
47
|
+
private readonly packetId;
|
|
48
|
+
/**
|
|
49
|
+
* Defines a new binary packet. \
|
|
50
|
+
* Make sure that every `packetId` is unique.
|
|
51
|
+
* @throws RangeError If packetId is negative, floating-point, or greater than 255.
|
|
52
|
+
*/
|
|
53
|
+
static define<T extends Definition>(packetId: number, definition?: T): BinaryPacket<T>;
|
|
54
|
+
private readonly entries;
|
|
55
|
+
readonly canFastWrite: boolean;
|
|
56
|
+
readonly minimumByteLength: number;
|
|
57
|
+
private constructor();
|
|
58
|
+
/**
|
|
59
|
+
* Reads/deserializes from the given Buffer. \
|
|
60
|
+
* Method available ONLY on NodeJS and Bun.
|
|
61
|
+
*
|
|
62
|
+
* If possible, always prefer reading using this method, as it is much faster than the other ones.
|
|
63
|
+
*
|
|
64
|
+
* NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \
|
|
65
|
+
* NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.
|
|
66
|
+
*/
|
|
67
|
+
readNodeBuffer(dataIn: Buffer, offsetPointer?: {
|
|
68
|
+
offset: number;
|
|
69
|
+
}, byteLength?: number): ToJson<T>;
|
|
70
|
+
/**
|
|
71
|
+
* Reads/deserializes from the given DataView.
|
|
72
|
+
*
|
|
73
|
+
* NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \
|
|
74
|
+
* NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.
|
|
75
|
+
*/
|
|
76
|
+
readDataView(dataIn: DataView, offsetPointer?: {
|
|
77
|
+
offset: number;
|
|
78
|
+
}, byteLength?: number): ToJson<T>;
|
|
79
|
+
/**
|
|
80
|
+
* Reads/deserializes from the given ArrayBuffer. \
|
|
81
|
+
* WARNING: this method is practically a HACK.
|
|
82
|
+
*
|
|
83
|
+
* When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \
|
|
84
|
+
* This is to prevent serious bugs and security issues. \
|
|
85
|
+
* That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.
|
|
86
|
+
*
|
|
87
|
+
* NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \
|
|
88
|
+
* NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.
|
|
89
|
+
*/
|
|
90
|
+
readArrayBuffer(dataIn: ArrayBuffer & {
|
|
91
|
+
buffer?: undefined;
|
|
92
|
+
}, byteOffset: number, byteLength: number): ToJson<T>;
|
|
93
|
+
/**
|
|
94
|
+
* Writes/serializes the given object into a Buffer. \
|
|
95
|
+
* Method available ONLY on NodeJS and Bun.
|
|
96
|
+
*
|
|
97
|
+
* If possible, always prefer writing using this method, as it is much faster than the other ones.
|
|
98
|
+
*/
|
|
99
|
+
writeNodeBuffer(dataOut: ToJson<T>): Buffer;
|
|
100
|
+
/**
|
|
101
|
+
* Writes/serializes the given object into a DataView. \
|
|
102
|
+
*/
|
|
103
|
+
writeDataView(dataOut: ToJson<T>): DataView;
|
|
104
|
+
/**
|
|
105
|
+
* Writes/serializes the given object into an ArrayBuffer. \
|
|
106
|
+
* This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \
|
|
107
|
+
*
|
|
108
|
+
* This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \
|
|
109
|
+
* Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \
|
|
110
|
+
*
|
|
111
|
+
* Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \
|
|
112
|
+
* For more information read the `readArrayBuffer` documentation.
|
|
113
|
+
*/
|
|
114
|
+
writeArrayBuffer(dataOut: ToJson<T>): {
|
|
115
|
+
buffer: ArrayBufferLike;
|
|
116
|
+
byteLength: number;
|
|
117
|
+
byteOffset: number;
|
|
118
|
+
};
|
|
119
|
+
private read;
|
|
120
|
+
private write;
|
|
121
|
+
private fastWrite;
|
|
122
|
+
/**
|
|
123
|
+
* The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
|
|
124
|
+
* But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
|
|
125
|
+
*/
|
|
126
|
+
private slowWrite;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* BinaryPacket definition: \
|
|
130
|
+
* Any packet can be defined through a "schema" object explaining its fields names and types.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* // Imagine we have a game board where each cell is a square and is one unit big.
|
|
134
|
+
* // A cell can be then defined by its X and Y coordinates.
|
|
135
|
+
* // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
|
|
136
|
+
* const Cell = {
|
|
137
|
+
* x: Field.UNSIGNED_INT_8,
|
|
138
|
+
* y: Field.UNSIGNED_INT_8
|
|
139
|
+
* }
|
|
140
|
+
*
|
|
141
|
+
* // When done with the cell definition we can create its BinaryPacket writer/reader.
|
|
142
|
+
* // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
143
|
+
* const CellPacket = BinaryPacket.define(0, Cell)
|
|
144
|
+
*
|
|
145
|
+
* // Let's now make the definition of the whole game board.
|
|
146
|
+
* // You can also specify arrays of both "primitive" fields and other BinaryPackets.
|
|
147
|
+
* const Board = {
|
|
148
|
+
* numPlayers: Field.UNSIGNED_INT_8,
|
|
149
|
+
* cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
|
|
150
|
+
* }
|
|
151
|
+
*
|
|
152
|
+
* // When done with the board definition we can create its BinaryPacket writer/reader.
|
|
153
|
+
* // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
154
|
+
* const BoardPacket = BinaryPacket.define(1, Board)
|
|
155
|
+
*
|
|
156
|
+
* // And use it.
|
|
157
|
+
* const buffer = BoardPacket.writeNodeBuffer({
|
|
158
|
+
* numPlayers: 1,
|
|
159
|
+
* cells: [
|
|
160
|
+
* { x: 0, y: 0 },
|
|
161
|
+
* { x: 1, y: 1 }
|
|
162
|
+
* ]
|
|
163
|
+
* })
|
|
164
|
+
*
|
|
165
|
+
* // sendTheBufferOver(buffer)
|
|
166
|
+
* // ...
|
|
167
|
+
* // const buffer = receiveTheBuffer()
|
|
168
|
+
* const board = BoardPacket.readNodeBuffer(buffer)
|
|
169
|
+
* // ...
|
|
170
|
+
*/
|
|
171
|
+
type Definition = {
|
|
172
|
+
[fieldName: string]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[];
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* 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. \
|
|
176
|
+
*/
|
|
177
|
+
type ToJson<T extends Definition> = {
|
|
178
|
+
[K in keyof T]: T[K] extends ReadonlyArray<infer Item> ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export { BinaryPacket, type Definition, Field, FieldArray };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
declare const enum Field {
|
|
2
|
+
/**
|
|
3
|
+
* Defines a 1 byte (8 bits) unsigned integer field. \
|
|
4
|
+
* (Range: 0 - 255)
|
|
5
|
+
*/
|
|
6
|
+
UNSIGNED_INT_8 = 0,
|
|
7
|
+
/**
|
|
8
|
+
* Defines a 2 bytes (16 bits) unsigned integer field. \
|
|
9
|
+
* (Range: 0 - 65535)
|
|
10
|
+
*/
|
|
11
|
+
UNSIGNED_INT_16 = 1,
|
|
12
|
+
/**
|
|
13
|
+
* Defines a 4 bytes (32 bits) unsigned integer field. \
|
|
14
|
+
* (Range: 0 - 4294967295)
|
|
15
|
+
*/
|
|
16
|
+
UNSIGNED_INT_32 = 2,
|
|
17
|
+
/**
|
|
18
|
+
* Defines a 1 byte (8 bits) signed integer field. \
|
|
19
|
+
* (Range: -128 - 127)
|
|
20
|
+
*/
|
|
21
|
+
INT_8 = 3,
|
|
22
|
+
/**
|
|
23
|
+
* Defines a 2 bytes (16 bits) signed integer field. \
|
|
24
|
+
* (Range: -32768 - 32767)
|
|
25
|
+
*/
|
|
26
|
+
INT_16 = 4,
|
|
27
|
+
/**
|
|
28
|
+
* Defines a 4 bytes (32 bits) signed integer field. \
|
|
29
|
+
* (Range: -2147483648 - 2147483647)
|
|
30
|
+
*/
|
|
31
|
+
INT_32 = 5,
|
|
32
|
+
/**
|
|
33
|
+
* Defines a 4 bytes (32 bits) floating-point field. \
|
|
34
|
+
*/
|
|
35
|
+
FLOAT_32 = 6,
|
|
36
|
+
/**
|
|
37
|
+
* Defines a 8 bytes (64 bits) floating-point field. \
|
|
38
|
+
*/
|
|
39
|
+
FLOAT_64 = 7
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Defines an array of a certain type. \
|
|
43
|
+
* As of now, only arrays with at most 256 elements are supported.
|
|
44
|
+
*/
|
|
45
|
+
declare function FieldArray<T extends Field | BinaryPacket<Definition>>(item: T): T[];
|
|
46
|
+
declare class BinaryPacket<T extends Definition> {
|
|
47
|
+
private readonly packetId;
|
|
48
|
+
/**
|
|
49
|
+
* Defines a new binary packet. \
|
|
50
|
+
* Make sure that every `packetId` is unique.
|
|
51
|
+
* @throws RangeError If packetId is negative, floating-point, or greater than 255.
|
|
52
|
+
*/
|
|
53
|
+
static define<T extends Definition>(packetId: number, definition?: T): BinaryPacket<T>;
|
|
54
|
+
private readonly entries;
|
|
55
|
+
readonly canFastWrite: boolean;
|
|
56
|
+
readonly minimumByteLength: number;
|
|
57
|
+
private constructor();
|
|
58
|
+
/**
|
|
59
|
+
* Reads/deserializes from the given Buffer. \
|
|
60
|
+
* Method available ONLY on NodeJS and Bun.
|
|
61
|
+
*
|
|
62
|
+
* If possible, always prefer reading using this method, as it is much faster than the other ones.
|
|
63
|
+
*
|
|
64
|
+
* NOTE: if you have an ArrayBuffer do not bother wrapping it into a node Buffer yourself. \
|
|
65
|
+
* NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.
|
|
66
|
+
*/
|
|
67
|
+
readNodeBuffer(dataIn: Buffer, offsetPointer?: {
|
|
68
|
+
offset: number;
|
|
69
|
+
}, byteLength?: number): ToJson<T>;
|
|
70
|
+
/**
|
|
71
|
+
* Reads/deserializes from the given DataView.
|
|
72
|
+
*
|
|
73
|
+
* NOTE: if you have an ArrayBuffer do not bother wrapping it into a DataView yourself. \
|
|
74
|
+
* NOTE: if you have an ArrayBuffer use the appropriate `readArrayBuffer`.
|
|
75
|
+
*/
|
|
76
|
+
readDataView(dataIn: DataView, offsetPointer?: {
|
|
77
|
+
offset: number;
|
|
78
|
+
}, byteLength?: number): ToJson<T>;
|
|
79
|
+
/**
|
|
80
|
+
* Reads/deserializes from the given ArrayBuffer. \
|
|
81
|
+
* WARNING: this method is practically a HACK.
|
|
82
|
+
*
|
|
83
|
+
* When using this method both the `byteOffset` and `byteLength` are REQUIRED and cannot be defaulted. \
|
|
84
|
+
* This is to prevent serious bugs and security issues. \
|
|
85
|
+
* That is because often raw ArrayBuffers come from a pre-allocated buffer pool and do not start at byteOffset 0.
|
|
86
|
+
*
|
|
87
|
+
* NOTE: if you have a node Buffer do not bother wrapping it into an ArrayBuffer yourself. \
|
|
88
|
+
* NOTE: if you have a node Buffer use the appropriate `readNodeBuffer` as it is much faster and less error prone.
|
|
89
|
+
*/
|
|
90
|
+
readArrayBuffer(dataIn: ArrayBuffer & {
|
|
91
|
+
buffer?: undefined;
|
|
92
|
+
}, byteOffset: number, byteLength: number): ToJson<T>;
|
|
93
|
+
/**
|
|
94
|
+
* Writes/serializes the given object into a Buffer. \
|
|
95
|
+
* Method available ONLY on NodeJS and Bun.
|
|
96
|
+
*
|
|
97
|
+
* If possible, always prefer writing using this method, as it is much faster than the other ones.
|
|
98
|
+
*/
|
|
99
|
+
writeNodeBuffer(dataOut: ToJson<T>): Buffer;
|
|
100
|
+
/**
|
|
101
|
+
* Writes/serializes the given object into a DataView. \
|
|
102
|
+
*/
|
|
103
|
+
writeDataView(dataOut: ToJson<T>): DataView;
|
|
104
|
+
/**
|
|
105
|
+
* Writes/serializes the given object into an ArrayBuffer. \
|
|
106
|
+
* This method is just a wrapper around either `writeNodeBuffer` or `writeDataView`. \
|
|
107
|
+
*
|
|
108
|
+
* This method works with JavaScript standard raw ArrayBuffer(s) and, as such, is very error prone: \
|
|
109
|
+
* Make sure you're using the returned byteLength and byteOffset fields in the read counterpart. \
|
|
110
|
+
*
|
|
111
|
+
* Always consider whether is possible to use directly `writeNodeBuffer` or `writeDataView` instead of `writeArrayBuffer`. \
|
|
112
|
+
* For more information read the `readArrayBuffer` documentation.
|
|
113
|
+
*/
|
|
114
|
+
writeArrayBuffer(dataOut: ToJson<T>): {
|
|
115
|
+
buffer: ArrayBufferLike;
|
|
116
|
+
byteLength: number;
|
|
117
|
+
byteOffset: number;
|
|
118
|
+
};
|
|
119
|
+
private read;
|
|
120
|
+
private write;
|
|
121
|
+
private fastWrite;
|
|
122
|
+
/**
|
|
123
|
+
* The slow writing path tries writing data into the buffer as fast as the fast writing path does. \
|
|
124
|
+
* But, if a non-empty array is encountered, the buffer needs to grow, slightly reducing performance.
|
|
125
|
+
*/
|
|
126
|
+
private slowWrite;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* BinaryPacket definition: \
|
|
130
|
+
* Any packet can be defined through a "schema" object explaining its fields names and types.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* // Imagine we have a game board where each cell is a square and is one unit big.
|
|
134
|
+
* // A cell can be then defined by its X and Y coordinates.
|
|
135
|
+
* // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
|
|
136
|
+
* const Cell = {
|
|
137
|
+
* x: Field.UNSIGNED_INT_8,
|
|
138
|
+
* y: Field.UNSIGNED_INT_8
|
|
139
|
+
* }
|
|
140
|
+
*
|
|
141
|
+
* // When done with the cell definition we can create its BinaryPacket writer/reader.
|
|
142
|
+
* // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
143
|
+
* const CellPacket = BinaryPacket.define(0, Cell)
|
|
144
|
+
*
|
|
145
|
+
* // Let's now make the definition of the whole game board.
|
|
146
|
+
* // You can also specify arrays of both "primitive" fields and other BinaryPackets.
|
|
147
|
+
* const Board = {
|
|
148
|
+
* numPlayers: Field.UNSIGNED_INT_8,
|
|
149
|
+
* cells: FieldArray(CellPacket) // equivalent to { cells: [CellPacket] }
|
|
150
|
+
* }
|
|
151
|
+
*
|
|
152
|
+
* // When done with the board definition we can create its BinaryPacket writer/reader.
|
|
153
|
+
* // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
|
|
154
|
+
* const BoardPacket = BinaryPacket.define(1, Board)
|
|
155
|
+
*
|
|
156
|
+
* // And use it.
|
|
157
|
+
* const buffer = BoardPacket.writeNodeBuffer({
|
|
158
|
+
* numPlayers: 1,
|
|
159
|
+
* cells: [
|
|
160
|
+
* { x: 0, y: 0 },
|
|
161
|
+
* { x: 1, y: 1 }
|
|
162
|
+
* ]
|
|
163
|
+
* })
|
|
164
|
+
*
|
|
165
|
+
* // sendTheBufferOver(buffer)
|
|
166
|
+
* // ...
|
|
167
|
+
* // const buffer = receiveTheBuffer()
|
|
168
|
+
* const board = BoardPacket.readNodeBuffer(buffer)
|
|
169
|
+
* // ...
|
|
170
|
+
*/
|
|
171
|
+
type Definition = {
|
|
172
|
+
[fieldName: string]: Field | Field[] | BinaryPacket<Definition> | BinaryPacket<Definition>[];
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* 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. \
|
|
176
|
+
*/
|
|
177
|
+
type ToJson<T extends Definition> = {
|
|
178
|
+
[K in keyof T]: T[K] extends ReadonlyArray<infer Item> ? Item extends BinaryPacket<infer BPDef> ? ToJson<BPDef>[] : number[] : T[K] extends BinaryPacket<infer BPDef> ? ToJson<BPDef> : number;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export { BinaryPacket, type Definition, Field, FieldArray };
|