-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8-manually.js
36 lines (28 loc) · 931 Bytes
/
8-manually.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
'use strict';
const ID_LENGTH = 4;
const encodeChunk = (id, payload) => {
const chunkView = new Uint8Array(ID_LENGTH + payload.length);
const view = new DataView(chunkView.buffer);
view.setInt32(0, id);
chunkView.set(payload, ID_LENGTH);
return chunkView;
};
const decodeChunk = (chunkView) => {
const view = new DataView(chunkView.buffer);
const id = view.getInt32(0);
const payload = chunkView.subarray(ID_LENGTH);
return { id, payload };
};
// Usage example
const encoder = new TextEncoder();
const data = encoder.encode('Hello World');
const packet = encodeChunk(123, data);
console.log(packet);
const { id, payload } = decodeChunk(packet);
const decoder = new TextDecoder();
const text = decoder.decode(payload);
console.log({ id, payload: text });
const assert = require('node:assert/strict');
assert.equal(id, 123);
assert.equal(text, 'Hello World');
module.exports = { encodeChunk, decodeChunk };