-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
51 lines (45 loc) · 1.08 KB
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var endBuffer = Buffer.from("\n");
function PacketWrapper() {
/**
* @type Buffer
*/
this.chunk = null;
}
/**
* @param {Buufer} chunk
*/
PacketWrapper.prototype.addChunk = function(chunk) {
if (this.chunk) {
this.chunk = Buffer.concat([this.chunk, chunk]);
} else {
this.chunk = chunk;
}
};
/**
* @returns {Buffer|null}
*/
PacketWrapper.prototype.read = function() {
if (!this.chunk) return null;
var length = this.chunk.readInt32BE();
if (this.chunk.length < length) return null;
var chunk = this.chunk.slice(4, length - 1);
if (this.chunk.length === length) {
this.chunk = null;
} else {
this.chunk = this.chunk.slice(length);
}
return chunk;
};
PacketWrapper.prototype.encode = function(buffer) {
return PacketWrapper.encode(buffer);
};
/**
* @param {Buufer|string} chunk
*/
PacketWrapper.encode = function(buffer) {
if (typeof buffer === "string") buffer = Buffer.from(buffer);
buffer = Buffer.concat([Buffer.allocUnsafe(4), buffer, endBuffer]);
buffer.writeInt32BE(buffer.length);
return buffer;
};
module.exports = PacketWrapper;