1 |
|
2 |
|
3 | exports.EncodeBuffer = EncodeBuffer;
|
4 |
|
5 | var MIN_BUFFER_SIZE = 2048;
|
6 | var MAX_BUFFER_SIZE = 65536;
|
7 | var DEFAULT_OPTIONS = {};
|
8 |
|
9 | function EncodeBuffer(options) {
|
10 | if (!(this instanceof EncodeBuffer)) return new EncodeBuffer(options);
|
11 | this.options = options || DEFAULT_OPTIONS;
|
12 | }
|
13 |
|
14 | EncodeBuffer.prototype.push = function(chunk) {
|
15 | var buffers = this.buffers || (this.buffers = []);
|
16 | buffers.push(chunk);
|
17 | };
|
18 |
|
19 | EncodeBuffer.prototype.read = function() {
|
20 | this.flush();
|
21 | var buffers = this.buffers;
|
22 | if (!buffers) return;
|
23 | var chunk = buffers.length > 1 ? Buffer.concat(buffers) : buffers[0];
|
24 | buffers.length = 0;
|
25 | return chunk;
|
26 | };
|
27 |
|
28 | EncodeBuffer.prototype.flush = function() {
|
29 | if (this.start < this.offset) {
|
30 | this.push(this.buffer.slice(this.start, this.offset));
|
31 | this.start = this.offset;
|
32 | }
|
33 | };
|
34 |
|
35 | EncodeBuffer.prototype.reserve = function(length) {
|
36 | if (!this.buffer) return this.alloc(length);
|
37 |
|
38 | var size = this.buffer.length;
|
39 |
|
40 |
|
41 | if (this.offset + length < size) return;
|
42 |
|
43 |
|
44 | if (this.offset) this.flush();
|
45 |
|
46 |
|
47 | this.alloc(Math.max(length, Math.min(size * 2, MAX_BUFFER_SIZE)));
|
48 | };
|
49 |
|
50 | EncodeBuffer.prototype.alloc = function(length) {
|
51 |
|
52 | this.buffer = new Buffer(length > MIN_BUFFER_SIZE ? length : MIN_BUFFER_SIZE);
|
53 | this.start = 0;
|
54 | this.offset = 0;
|
55 | };
|
56 |
|
57 | EncodeBuffer.prototype.send = function(buffer) {
|
58 | var end = this.offset + buffer.length;
|
59 | if (this.buffer && end < this.buffer.length) {
|
60 | buffer.copy(this.buffer, this.offset);
|
61 | this.offset = end;
|
62 | } else {
|
63 | this.flush();
|
64 | this.push(buffer);
|
65 | }
|
66 | };
|