Skip to content

Commit

Permalink
fix: using Buffer.alloc(size) instead of new Buffer(size)
Browse files Browse the repository at this point in the history
  • Loading branch information
gxcsoccer committed May 15, 2018
1 parent d0cf375 commit 3645313
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -3,6 +3,6 @@ node_js:
- '4'
- '6'
- '8'
- '9'
- '10'
script: "npm run test-travis"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
22 changes: 13 additions & 9 deletions lib/byte.js
Expand Up @@ -21,7 +21,7 @@ function ByteBuffer(options) {
if (array) {
this._bytes = array;
} else {
this._bytes = new Buffer(this._size);
this._bytes = allocBuffer(this._size);
}
}

Expand Down Expand Up @@ -57,12 +57,7 @@ ByteBuffer.prototype._checkSize = function (afterSize) {
this._size = afterSize * 2;
this._limit = this._size;
debug('allocate new Buffer: from %d to %d bytes', old, this._size);
var bytes;
if (Buffer.allocUnsafe) {
bytes = Buffer.allocUnsafe(this._size);
} else {
bytes = new Buffer(this._size);
}
var bytes = allocBuffer(this._size);
this._bytes.copy(bytes, 0);
this._bytes = bytes;
};
Expand Down Expand Up @@ -400,7 +395,7 @@ ByteBuffer.prototype._copy = function (start, end) {
// if (end - start > 2048) {
// return this._bytes.slice(start, end);
// }
var buf = new Buffer(end - start);
var buf = allocBuffer(end - start);
this._bytes.copy(buf, 0, start, end);
return buf;
};
Expand Down Expand Up @@ -594,7 +589,7 @@ ByteBuffer.prototype.flip = function () {
ByteBuffer.prototype.clear = function () {
this._limit = this._size;
this._offset = 0;
this._bytes = new Buffer(this._size);
this._bytes = allocBuffer(this._size);
return this;
}

Expand Down Expand Up @@ -637,4 +632,13 @@ ByteBuffer.prototype.checkForUnderflow = function (length) {
}
};

function allocBuffer(size) {
if (Buffer.alloc) {
return Buffer.alloc(size);
}
var buf = new Buffer(size);
buf.fill(0);
return buf;
}

module.exports = ByteBuffer;
4 changes: 2 additions & 2 deletions test/byte.test.js
Expand Up @@ -757,7 +757,7 @@ describe('byte.test.js', function () {
var buf2 = new Buffer(1);
assert.throws(function() {
bytes.get(buf2);
}, 'BufferOverflowException');
}, null, 'BufferOverflowException');
});

it('should get(dst, offset, length) again', function () {
Expand Down Expand Up @@ -793,7 +793,7 @@ describe('byte.test.js', function () {
bytes.put(0xfd);
assert.throws(function () {
bytes.getRawStringByStringLength(0, str.length + 1);
}, 'string is not valid UTF-8 encode');
}, null, 'string is not valid UTF-8 encode');
});
});

Expand Down

0 comments on commit 3645313

Please sign in to comment.