forked from mqttjs/mqtt-packet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.js
57 lines (46 loc) · 1.14 KB
/
generate.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
'use strict';
var writeToStream = require('./writeToStream')
, EE = require('events').EventEmitter
, inherits = require('inherits')
function generate(packet) {
var stream = new Accumulator()
writeToStream(packet, stream)
return stream.concat()
}
function Accumulator() {
this._array = new Array(20)
this._i = 0
}
inherits(Accumulator, EE)
Accumulator.prototype.write = function (chunk) {
this._array[this._i++] = chunk
return true
};
Accumulator.prototype.concat = function () {
var length = 0
, lengths = new Array(this._array.length)
, list = this._array
, pos = 0
, i
, result;
for (i = 0; i < list.length && list[i]; i++) {
if (typeof list[i] !== 'string') {
lengths[i] = list[i].length;
} else {
lengths[i] = Buffer.byteLength(list[i]);
}
length += lengths[i];
}
result = new Buffer(length);
for (i = 0; i < list.length && list[i]; i++) {
if (typeof list[i] !== 'string') {
list[i].copy(result, pos);
pos += lengths[i];
} else {
result.write(list[i], pos);
pos += lengths[i];
}
}
return result;
};
module.exports = generate