cgserver 13.3.0 → 13.3.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/README.md
CHANGED
|
@@ -3,33 +3,51 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.PacketParser = void 0;
|
|
4
4
|
class PacketParser {
|
|
5
5
|
buffer;
|
|
6
|
-
offset;
|
|
7
6
|
constructor() {
|
|
8
7
|
this.buffer = Buffer.alloc(0);
|
|
9
|
-
this.offset = 0;
|
|
10
8
|
}
|
|
11
9
|
push(chunk) {
|
|
12
|
-
|
|
13
|
-
this.buffer.
|
|
14
|
-
chunk.copy(newBuffer, this.buffer.length);
|
|
15
|
-
this.buffer = newBuffer;
|
|
10
|
+
// Use Buffer.concat which is concise and optimized internally
|
|
11
|
+
this.buffer = Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length);
|
|
16
12
|
}
|
|
17
13
|
parse() {
|
|
14
|
+
// Need at least 4 bytes for length header
|
|
18
15
|
if (this.buffer.length < 4)
|
|
19
16
|
return null;
|
|
20
17
|
// Read packet length (first 4 bytes)
|
|
21
18
|
const length = this.buffer.readUInt32BE(0);
|
|
19
|
+
// Not enough data yet
|
|
22
20
|
if (this.buffer.length < length + 4)
|
|
23
21
|
return null;
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
//
|
|
27
|
-
|
|
22
|
+
const start = 4;
|
|
23
|
+
const end = 4 + length;
|
|
24
|
+
// Copy packet out so callers don't keep a view into the large backing buffer
|
|
25
|
+
const packet = Buffer.from(this.buffer.slice(start, end));
|
|
26
|
+
// Remove parsed data from buffer. We try to avoid keeping a large backing
|
|
27
|
+
// buffer alive by compacting the remainder when it's small relative to the
|
|
28
|
+
// previous buffer.
|
|
29
|
+
const remainderLen = this.buffer.length - end;
|
|
30
|
+
if (remainderLen <= 0) {
|
|
31
|
+
this.buffer = Buffer.alloc(0);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const remainder = this.buffer.slice(end);
|
|
35
|
+
// If remainder is much smaller than the previous buffer, copy it to
|
|
36
|
+
// release the old backing store. Otherwise keep the slice to avoid
|
|
37
|
+
// an extra copy.
|
|
38
|
+
if (remainderLen < (this.buffer.length >> 1)) {
|
|
39
|
+
this.buffer = Buffer.from(remainder);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
this.buffer = remainder;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
28
45
|
return packet;
|
|
29
46
|
}
|
|
30
47
|
pack(data) {
|
|
31
48
|
const length = data.length;
|
|
32
|
-
|
|
49
|
+
// allocUnsafe for slight perf improvement; we write every byte below
|
|
50
|
+
const packet = Buffer.allocUnsafe(length + 4);
|
|
33
51
|
// Write length header
|
|
34
52
|
packet.writeUInt32BE(length, 0);
|
|
35
53
|
// Write data
|