Skip to content

Commit

Permalink
use safe-buffer and Buffer.from to ensure we're actually using a copy…
Browse files Browse the repository at this point in the history
… of the buffer
  • Loading branch information
rubensayshi committed Aug 3, 2017
1 parent 540abd6 commit ef6aeb4
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
var Buffer = require('safe-buffer').Buffer
module.exports = function reverse (src) {
if (typeof src.reverse === 'function') {
return src.reverse()
return Buffer.from(src).reverse()
} else {
var buffer = new Buffer(src.length)
var buffer = Buffer.alloc(src.length)

for (var i = 0, j = src.length - 1; i <= j; ++i, --j) {
buffer[i] = src[j]
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,8 @@
"devDependencies": {
"standard": "*",
"tape": "*"
},
"dependencies": {
"safe-buffer": "^5.1.1"
}
}
5 changes: 3 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
var Buffer = require('safe-buffer').Buffer
var test = require('tape')
var reverse = require('../')
var reverseInplace = require('../inplace')
Expand All @@ -6,7 +7,7 @@ var fixtures = require('./fixtures')
test('reverse', function (t) {
fixtures.forEach(function (f) {
t.test('returns ' + f.expected + ' for ' + f.a, function (t) {
var a = new Buffer(f.a, 'hex')
var a = Buffer.from(f.a, 'hex')
t.same(reverse(a).toString('hex'), f.expected)
t.same(a.toString('hex'), f.a) // input unchanged
t.end()
Expand All @@ -19,7 +20,7 @@ test('reverse', function (t) {
test('reverse/inplace', function (t) {
fixtures.forEach(function (f) {
t.test('returns ' + f.expected + ' for ' + f.a, function (t) {
var a = new Buffer(f.a, 'hex')
var a = Buffer.from(f.a, 'hex')
t.same(reverseInplace(a).toString('hex'), f.expected)
t.same(a.toString('hex'), f.expected) // input mutated
t.end()
Expand Down

0 comments on commit ef6aeb4

Please sign in to comment.