Use Buffer.write() instead of Buffer.copy() to write strings into buffers.

This commit is contained in:
James Coglan
2019-05-24 17:22:51 +01:00
parent 4b4cb871bb
commit f27aa59fd8
3 changed files with 7 additions and 29 deletions
+4 -4
View File
@@ -86,12 +86,12 @@ var instance = {
if (typeof buffer !== 'string') buffer = buffer.toString();
var payload = Buffer.from(buffer, 'utf8'),
frame = Buffer.allocUnsafe(payload.length + 2);
var length = Buffer.byteLength(buffer),
frame = Buffer.allocUnsafe(length + 2);
frame[0] = 0x00;
frame[payload.length + 1] = 0xFF;
payload.copy(frame, 1);
frame.write(buffer, 1);
frame[frame.length - 1] = 0xFF;
this._write(frame);
return true;
+1 -10
View File
@@ -13,16 +13,7 @@ var Message = function() {
var instance = {
read: function() {
if (this.data) return this.data;
this.data = Buffer.allocUnsafe(this.length);
var offset = 0;
for (var i = 0, n = this._chunks.length; i < n; i++) {
this._chunks[i].copy(this.data, offset);
offset += this._chunks[i].length;
}
return this.data;
return this.data = this.data || Buffer.concat(this._chunks, this.length);
},
pushFrame: function(frame) {
+2 -15
View File
@@ -10,7 +10,7 @@ var StreamReader = function() {
StreamReader.prototype.put = function(buffer) {
if (!buffer || buffer.length === 0) return;
if (!buffer.copy) buffer = Buffer.from(buffer);
if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer);
this._queue.push(buffer);
this._queueSize += buffer.length;
};
@@ -46,7 +46,7 @@ StreamReader.prototype.read = function(length) {
buffers.push(queue[0].slice(0, remain));
queue[0] = queue[0].slice(remain);
}
return this._concat(buffers, length);
return Buffer.concat(buffers, length);
};
StreamReader.prototype.eachByte = function(callback, context) {
@@ -66,17 +66,4 @@ StreamReader.prototype.eachByte = function(callback, context) {
}
};
StreamReader.prototype._concat = function(buffers, length) {
if (Buffer.concat) return Buffer.concat(buffers, length);
var buffer = Buffer.allocUnsafe(length),
offset = 0;
for (var i = 0, n = buffers.length; i < n; i++) {
buffers[i].copy(buffer, offset);
offset += buffers[i].length;
}
return buffer;
};
module.exports = StreamReader;