UNPKG

1.66 kBJavaScriptView Raw
1// encode-buffer.js
2
3exports.EncodeBuffer = EncodeBuffer;
4
5var MIN_BUFFER_SIZE = 2048;
6var MAX_BUFFER_SIZE = 65536;
7var DEFAULT_OPTIONS = {};
8
9function EncodeBuffer(options) {
10 if (!(this instanceof EncodeBuffer)) return new EncodeBuffer(options);
11 this.options = options || DEFAULT_OPTIONS;
12}
13
14EncodeBuffer.prototype.push = function(chunk) {
15 var buffers = this.buffers || (this.buffers = []);
16 buffers.push(chunk);
17};
18
19EncodeBuffer.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
28EncodeBuffer.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
35EncodeBuffer.prototype.reserve = function(length) {
36 if (!this.buffer) return this.alloc(length);
37
38 var size = this.buffer.length;
39
40 // is it long enough?
41 if (this.offset + length < size) return;
42
43 // flush current buffer
44 if (this.offset) this.flush();
45
46 // resize it to 2x current length
47 this.alloc(Math.max(length, Math.min(size * 2, MAX_BUFFER_SIZE)));
48};
49
50EncodeBuffer.prototype.alloc = function(length) {
51 // allocate new buffer
52 this.buffer = new Buffer(length > MIN_BUFFER_SIZE ? length : MIN_BUFFER_SIZE);
53 this.start = 0;
54 this.offset = 0;
55};
56
57EncodeBuffer.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};