forked from bnoordhuis/node-buffertools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffertools.js
More file actions
90 lines (74 loc) · 2.03 KB
/
buffertools.js
File metadata and controls
90 lines (74 loc) · 2.03 KB
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
buffertools = require('./build/Release/buffertools.node');
SlowBuffer = require('buffer').SlowBuffer;
Buffer = require('buffer').Buffer;
// requires node 3.1
events = require('events');
util = require('util');
// extend object prototypes
for (var key in buffertools) {
var val = buffertools[key];
SlowBuffer.prototype[key] = val;
Buffer.prototype[key] = val;
exports[key] = val;
}
// bug fix, see https://github.com/bnoordhuis/node-buffertools/issues/#issue/6
Buffer.prototype.concat = SlowBuffer.prototype.concat = function() {
var args = [this].concat(Array.prototype.slice.call(arguments));
return buffertools.concat.apply(buffertools, args);
};
//
// WritableBufferStream
//
// - never emits 'error'
// - never emits 'drain'
//
function WritableBufferStream() {
this.writable = true;
this.buffer = null;
}
util.inherits(WritableBufferStream, events.EventEmitter);
WritableBufferStream.prototype._append = function(buffer, encoding) {
if (!this.writable) {
throw new Error('Stream is not writable.');
}
if (Buffer.isBuffer(buffer)) {
// no action required
}
else if (typeof buffer == 'string') {
// TODO optimize
buffer = new Buffer(buffer, encoding || 'utf8');
}
else {
throw new Error('Argument should be either a buffer or a string.');
}
// FIXME optimize!
if (this.buffer) {
this.buffer = buffertools.concat(this.buffer, buffer);
}
else {
this.buffer = new Buffer(buffer.length);
buffer.copy(this.buffer);
}
};
WritableBufferStream.prototype.write = function(buffer, encoding) {
this._append(buffer, encoding);
// signal that it's safe to immediately write again
return true;
};
WritableBufferStream.prototype.end = function(buffer, encoding) {
if (buffer) {
this._append(buffer, encoding);
}
this.emit('close');
this.writable = false;
};
WritableBufferStream.prototype.getBuffer = function() {
if (this.buffer) {
return this.buffer;
}
return new Buffer(0);
};
WritableBufferStream.prototype.toString = function() {
return this.getBuffer().toString();
};
exports.WritableBufferStream = WritableBufferStream;