binary-packet 1.1.0 → 1.2.1

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 CHANGED
@@ -1,61 +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
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 CHANGED
@@ -1,180 +1,211 @@
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
- ### Fields / Data types
23
-
24
- Currently, these kinds of `fields` are supported:
25
- | Type | Description | Values | Size (bytes) |
26
- |------|-------------|--------------|--------------|
27
- | `Field.UNSIGNED_INT_8` | 8 bits unsigned integer | 0 - 255 | 1 |
28
- | `Field.UNSIGNED_INT_16` | 16 bits unsigned integer | 0 - 65535 | 2 |
29
- | `Field.UNSIGNED_INT_32` | 32 bits unsigned integer | 0 - 4294967295 | 4 |
30
- | `Field.INT_8` | 8 bits signed integer | -128 - 127 | 1 |
31
- | `Field.INT_16` | 16 bits signed integer | -32768 - 32767 | 2 |
32
- | `Field.INT_32` | 32 bits signed integer | -2147483648 - 2147483647 | 4 |
33
- | `Field.FLOAT_32` | 32 bits IEEE754 floating-point | | 4 |
34
- | `Field.FLOAT_64` | 64 bits IEEE754 floating-point | | 8 |
35
- | `BinaryPacket` | BinaryPacket "subpacket" | BinaryPacket | size(BinaryPacket) |
36
- | `FieldString` | **ASCII** or **single octet utf-8 chars** string | Up to 65536 chars | 2 + length |
37
- | `FieldArray` | Dynamically-sized array of one of the types above | Up to 256 elements | 1 + length \* size(Element) |
38
- | `FieldFixedArray` | Statically-sized array of one of the types above | Any pre-defined numbers of elements | length \* size(Element) |
39
- | `FieldBitFlags` | Boolean flags packed into a single 8 bits integer | Up to 8 boolean flags | 1 |
40
- | `FieldOptional` | Optional BinaryPacket "subpacket" | BinaryPacket \| undefined | 1 + size(BinaryPacket) |
41
-
42
- As shown, both arrays and nested objects ("subpackets") are supported. \
43
- Note: `FieldFixedArray` is much more memory efficient and performant than `FieldArray`, but require a pre-defined length.
44
-
45
- ### Pattern matching
46
-
47
- The library exposes an easy way to "pattern match" packets of a **yet-unknown-type** in a type-safe manner through a `visitor` pattern. \
48
- For an example, search for "**pattern matching**" in the examples below.
49
-
50
- ## Usage Examples
51
-
52
- ### Example: (incomplete) definition of a simplistic board game
53
-
54
- ```typescript
55
- import { BinaryPacket, Field, FieldArray } from 'binary-packet'
56
-
57
- // Suppose we have a game board where each cell is a square and is one unit big.
58
- // A cell can be then defined by its X and Y coordinates.
59
- // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
60
- const Cell = {
61
- x: Field.UNSIGNED_INT_8,
62
- y: Field.UNSIGNED_INT_8
63
- }
64
-
65
- // When done with the cell definition we can create its BinaryPacket writer/reader.
66
- // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
67
- const CellPacket = BinaryPacket.define(0, Cell)
68
-
69
- // Let's now make the definition of the whole game board.
70
- // You can also specify arrays of both "primitive" fields and other BinaryPackets.
71
- const Board = {
72
- numPlayers: Field.UNSIGNED_INT_8,
73
- otherStuff: Field.INT_32,
74
- cells: FieldArray(CellPacket)
75
- }
76
-
77
- // When done with the board definition we can create its BinaryPacket writer/reader.
78
- // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
79
- const BoardPacket = BinaryPacket.define(1, Board)
80
-
81
- //////////////////
82
- // WRITING SIDE //
83
- //////////////////
84
- const buffer = BoardPacket.writeNodeBuffer({
85
- numPlayers: 1,
86
- otherStuff: 69420,
87
- cells: [
88
- { x: 0, y: 0 },
89
- { x: 1, y: 1 }
90
- ]
91
- })
92
-
93
- // ...
94
- // sendTheBufferOverTheNetwork(buffer)
95
- // ...
96
-
97
- //////////////////
98
- // READING SIDE //
99
- //////////////////
100
- import assert from 'assert'
101
-
102
- // ...
103
- // const buffer = receiveTheBufferFromTheNetwork()
104
- // ...
105
-
106
- const board = BoardPacket.readNodeBuffer(buffer)
107
-
108
- assert(board.numPlayers === 1)
109
- assert(board.otherStuff === 69420)
110
- assert(board.cells.length === 2)
111
- assert(board.cells[0].x === 0)
112
- assert(board.cells[0].y === 0)
113
- assert(board.cells[1].x === 1)
114
- assert(board.cells[1].y === 1)
115
- ```
116
-
117
- ### Example: pattern matching
118
-
119
- ```typescript
120
- import assert from 'assert/strict'
121
- import { BinaryPacket, Field } from 'binary-packet'
122
-
123
- // Packet A definition
124
- const A = BinaryPacket.define(1)
125
-
126
- // Packet B definition: This is the kind of packets that we care about in this example!
127
- const B = BinaryPacket.define(2, { data: Field.UNSIGNED_INT_8 })
128
-
129
- // Packet C definition
130
- const C = BinaryPacket.define(3)
131
-
132
- // Assume the following packet comes from the network or, for some other reason, is a buffer we do not know anything about.
133
- const buffer = B.writeNodeBuffer({ data: 255 })
134
-
135
- BinaryPacket.visitNodeBuffer(
136
- buffer,
137
-
138
- A.visitor(() => assert(false, 'Erroneously accepted visitor A')),
139
-
140
- B.visitor(packet => {
141
- // Do something with the packet
142
- assert.equal(packet.data, 255)
143
- console.log('Accepted visitor B:', packet)
144
- }),
145
-
146
- C.visitor(() => assert(false, 'Erroneously accepted visitor C'))
147
- )
148
- ```
149
-
150
- ## Benchmarks & Alternatives
151
-
152
- Benchmarks are not always meant to be taken seriously. \
153
- Most of the times the results of a benchmark do not actually show the full capabilities of each library. \
154
- 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.
155
-
156
- This library has been benchmarked against the following alternatives:
157
-
158
- - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular, fast and battle-tested library. Currently offers more features than binary-packet, but it always appears to be slower and is also less type-safe.
159
- - [restructure](https://www.npmjs.com/package/restructure) - An older, popular schema-based library, has some extra features like LazyArrays, but it is **much slower** than both binary-packet and msgpackr. And, sadly, easily crashes with complex structures.
160
-
161
- The benchmarks are executed on three different kinds of packets:
162
-
163
- - EmptyPacket: basically an empty javascript object.
164
- - SimplePacket: objects with just primitive fields, statically-sized arrays and a string.
165
- - ComplexPacket: objects with primitives, statically-sized arrays, dynamically-sized arrays, bitflags, a string, an array of strings and other nested objects/arrays.
166
-
167
- You can see and run the benchmarks yourself if you:
168
-
169
- - Clone the [repository](https://github.com/silence-cloud-com/binary-packet).
170
- - Launch `npm run benchmark`.
171
-
172
- ## Disclaimer
173
-
174
- This library is still very new, thus not "battle-tested" in production enough, or may still have missing important features. \
175
- 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) until this library becomes 100% production-ready.
176
-
177
- ## Contribute
178
-
179
- Would like to have more complex, but still hyper-fast and memory efficient, features? \
180
- [Contribute on GitHub](https://github.com/silence-cloud-com/binary-packet) yourself or, alternatively, [buy me a coffee](https://buymeacoffee.com/silence.cloud)!
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
+ ### Fields / Data types
23
+
24
+ Currently, these kinds of `fields` are supported:
25
+ | Type | Description | Values | Size (bytes) |
26
+ |------|-------------|--------------|--------------|
27
+ | `Field.UNSIGNED_INT_8` | 8 bits unsigned integer | 0 - 255 | 1 |
28
+ | `Field.UNSIGNED_INT_16` | 16 bits unsigned integer | 0 - 65535 | 2 |
29
+ | `Field.UNSIGNED_INT_32` | 32 bits unsigned integer | 0 - 4294967295 | 4 |
30
+ | `Field.INT_8` | 8 bits signed integer | -128 - 127 | 1 |
31
+ | `Field.INT_16` | 16 bits signed integer | -32768 - 32767 | 2 |
32
+ | `Field.INT_32` | 32 bits signed integer | -2147483648 - 2147483647 | 4 |
33
+ | `Field.FLOAT_32` | 32 bits IEEE754 floating-point | | 4 |
34
+ | `Field.FLOAT_64` | 64 bits IEEE754 floating-point | | 8 |
35
+ | `BinaryPacket` | BinaryPacket "subpacket" | BinaryPacket | size(BinaryPacket) |
36
+ | `FieldString` | **ASCII** or **single octet utf-8 chars** string | Up to 65536 chars | 2 + length |
37
+ | `FieldArray` | Dynamically-sized array of one of the types above | Up to 256 elements | 1 + length \* size(Element) |
38
+ | `FieldFixedArray` | Statically-sized array of one of the types above | Any pre-defined numbers of elements | length \* size(Element) |
39
+ | `FieldBitFlags` | Boolean flags packed into a single 8 bits integer | Up to 8 boolean flags | 1 |
40
+ | `FieldOptional` | Optional BinaryPacket "subpacket" | BinaryPacket \| undefined | 1 + size(BinaryPacket) |
41
+
42
+ As shown, both arrays and nested objects ("subpackets") are supported. \
43
+ Note: `FieldFixedArray` is much more memory efficient and performant than `FieldArray`, but require a pre-defined length.
44
+
45
+ ### Pattern matching
46
+
47
+ The library exposes an easy way to "pattern match" packets of a **yet-unknown-type** in a type-safe manner through a `visitor` pattern. \
48
+ For an example, search for "**pattern matching**" in the examples below.
49
+
50
+ ## Usage Examples
51
+
52
+ ### Example: (incomplete) definition of a simplistic board game
53
+
54
+ ```typescript
55
+ import { BinaryPacket, Field, FieldArray } from 'binary-packet'
56
+
57
+ // Suppose we have a game board where each cell is a square and is one unit big.
58
+ // A cell can be then defined by its X and Y coordinates.
59
+ // For simplicity, let's say there cannot be more than 256 cells, so we can use 8 bits for each coordinate.
60
+ const Cell = {
61
+ x: Field.UNSIGNED_INT_8,
62
+ y: Field.UNSIGNED_INT_8
63
+ }
64
+
65
+ // When done with the cell definition we can create its BinaryPacket writer/reader.
66
+ // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
67
+ const CellPacket = BinaryPacket.define(0, Cell)
68
+
69
+ // Let's now make the definition of the whole game board.
70
+ // You can also specify arrays of both "primitive" fields and other BinaryPackets.
71
+ const Board = {
72
+ numPlayers: Field.UNSIGNED_INT_8,
73
+ otherStuff: Field.INT_32,
74
+ cells: FieldArray(CellPacket)
75
+ }
76
+
77
+ // When done with the board definition we can create its BinaryPacket writer/reader.
78
+ // NOTE: each BinaryPacket needs an unique ID, for identification purposes and error checking.
79
+ const BoardPacket = BinaryPacket.define(1, Board)
80
+
81
+ //////////////////
82
+ // WRITING SIDE //
83
+ //////////////////
84
+ const buffer = BoardPacket.writeNodeBuffer({
85
+ numPlayers: 1,
86
+ otherStuff: 69420,
87
+ cells: [
88
+ { x: 0, y: 0 },
89
+ { x: 1, y: 1 }
90
+ ]
91
+ })
92
+
93
+ // ...
94
+ // sendTheBufferOverTheNetwork(buffer)
95
+ // ...
96
+
97
+ //////////////////
98
+ // READING SIDE //
99
+ //////////////////
100
+ import assert from 'assert'
101
+
102
+ // ...
103
+ // const buffer = receiveTheBufferFromTheNetwork()
104
+ // ...
105
+
106
+ const board = BoardPacket.readNodeBuffer(buffer)
107
+
108
+ assert(board.numPlayers === 1)
109
+ assert(board.otherStuff === 69420)
110
+ assert(board.cells.length === 2)
111
+ assert(board.cells[0].x === 0)
112
+ assert(board.cells[0].y === 0)
113
+ assert(board.cells[1].x === 1)
114
+ assert(board.cells[1].y === 1)
115
+ ```
116
+
117
+ ### Example: pattern matching
118
+
119
+ ```typescript
120
+ import assert from 'assert/strict'
121
+ import { BinaryPacket, Field } from 'binary-packet'
122
+
123
+ // Packet A definition
124
+ const A = BinaryPacket.define(1)
125
+
126
+ // Packet B definition: This is the kind of packets that we care about in this example!
127
+ const B = BinaryPacket.define(2, { data: Field.UNSIGNED_INT_8 })
128
+
129
+ // Packet C definition
130
+ const C = BinaryPacket.define(3)
131
+
132
+ // Assume the following packet comes from the network or, for some other reason, is a buffer we do not know anything about.
133
+ const buffer = B.writeNodeBuffer({ data: 255 })
134
+
135
+ BinaryPacket.visitNodeBuffer(
136
+ buffer,
137
+
138
+ A.visitor(() => assert(false, 'Erroneously accepted visitor A')),
139
+
140
+ B.visitor(packet => {
141
+ // Do something with the packet
142
+ assert.equal(packet.data, 255)
143
+ console.log('Accepted visitor B:', packet)
144
+ }),
145
+
146
+ C.visitor(() => assert(false, 'Erroneously accepted visitor C'))
147
+ )
148
+ ```
149
+
150
+ ## Sequential Serializer
151
+
152
+ This library also provides an opinionated way to serialize any javascript Iterable, as long as their size is known beforehand. \
153
+ This is extra convenient when dealing with such iterables because it allows serializing all the data without having to allocate for temporary arrays, which was necessary in previous versions and in many other similar libraries.
154
+
155
+ Usage:
156
+
157
+ ```typescript
158
+ // JavaScript Maps are Iterable, would also work with generators and custom classes that correctly implement the Iterable interface.
159
+ import { BinaryPacket, Field, FieldArray, SequentialSerializer } from 'binary-packet'
160
+
161
+ const Packet = BinaryPacket.define(0, {
162
+ numbers: FieldArray(Field.INT_32)
163
+ })
164
+
165
+ const map = new Map([
166
+ [1, 2],
167
+ [2, 4],
168
+ [3, 6]
169
+ ])
170
+
171
+ // Example serializer that serializes only the values of a map, without the overhead of intermediate arrays.
172
+ const serializer = new SequentialSerializer(map.values(), map.size)
173
+
174
+ const buffer = Packet.writeNodeBuffer({
175
+ numbers: serializer
176
+ })
177
+ ```
178
+
179
+ Note: if an array is already available, just use that instead. The SequentialSerializer is meant for more complex iterables.
180
+
181
+ ## Benchmarks & Alternatives
182
+
183
+ Benchmarks are not always meant to be taken seriously. \
184
+ Most of the times the results of a benchmark do not actually show the full capabilities of each library. \
185
+ 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.
186
+
187
+ This library has been benchmarked against the following alternatives:
188
+
189
+ - [msgpackr](https://www.npmjs.com/package/msgpackr) - A very popular, fast and battle-tested library. Currently offers more features than binary-packet, but it always appears to be slower and is also less type-safe.
190
+ - [restructure](https://www.npmjs.com/package/restructure) - An older, popular schema-based library, has some extra features like LazyArrays, but it is **much slower** than both binary-packet and msgpackr. And, sadly, easily crashes with complex structures.
191
+
192
+ The benchmarks are executed on three different kinds of packets:
193
+
194
+ - EmptyPacket: basically an empty javascript object.
195
+ - SimplePacket: objects with just primitive fields, statically-sized arrays and a string.
196
+ - ComplexPacket: objects with primitives, statically-sized arrays, dynamically-sized arrays, bitflags, a string, an array of strings and other nested objects/arrays.
197
+
198
+ You can see and run the benchmarks yourself if you:
199
+
200
+ - Clone the [repository](https://github.com/silence-cloud-com/binary-packet).
201
+ - Launch `npm run benchmark`.
202
+
203
+ ## Disclaimer
204
+
205
+ This library is still very new, thus not "battle-tested" in production enough, or may still have missing important features. \
206
+ 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) until this library becomes 100% production-ready.
207
+
208
+ ## Contribute
209
+
210
+ Would like to have more complex, but still hyper-fast and memory efficient, features? \
211
+ [Contribute on GitHub](https://github.com/silence-cloud-com/binary-packet) yourself or, alternatively, [buy me a coffee](https://buymeacoffee.com/silence.cloud)!