-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathserializer.js
98 lines (87 loc) · 2.27 KB
/
serializer.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const Transform = require('readable-stream').Transform
class Serializer extends Transform {
constructor (proto, mainType) {
super({ writableObjectMode: true })
this.proto = proto
this.mainType = mainType
this.queue = Buffer.alloc(0)
}
createPacketBuffer (packet) {
return this.proto.createPacketBuffer(this.mainType, packet)
}
_transform (chunk, enc, cb) {
let buf
try {
buf = this.createPacketBuffer(chunk)
} catch (e) {
return cb(e)
}
this.push(buf)
return cb()
}
}
class Parser extends Transform {
constructor (proto, mainType) {
super({ readableObjectMode: true })
this.proto = proto
this.mainType = mainType
this.queue = Buffer.alloc(0)
}
parsePacketBuffer (buffer) {
return this.proto.parsePacketBuffer(this.mainType, buffer)
}
_transform (chunk, enc, cb) {
this.queue = Buffer.concat([this.queue, chunk])
while (true) {
let packet
try {
packet = this.parsePacketBuffer(this.queue)
} catch (e) {
if (e.partialReadError) { return cb() } else {
e.buffer = this.queue
this.queue = Buffer.alloc(0)
return cb(e)
}
}
this.push(packet)
this.queue = this.queue.slice(packet.metadata.size)
}
}
}
class FullPacketParser extends Transform {
constructor (proto, mainType, noErrorLogging = false) {
super({ readableObjectMode: true })
this.proto = proto
this.mainType = mainType
this.noErrorLogging = noErrorLogging
}
parsePacketBuffer (buffer) {
return this.proto.parsePacketBuffer(this.mainType, buffer)
}
_transform (chunk, enc, cb) {
let packet
try {
packet = this.parsePacketBuffer(chunk)
if (packet.metadata.size !== chunk.length && !this.noErrorLogging) {
console.log('Chunk size is ' + chunk.length + ' but only ' + packet.metadata.size + ' was read ; partial packet : ' +
JSON.stringify(packet.data) + '; buffer :' + chunk.toString('hex'))
}
} catch (e) {
if (e.partialReadError) {
if (!this.noErrorLogging) {
console.log(e.stack)
}
return cb()
} else {
return cb(e)
}
}
this.push(packet)
cb()
}
}
module.exports = {
Serializer,
Parser,
FullPacketParser
}