From b436fda99c9ad31420c1d09f17b858087a740d87 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Tue, 31 Dec 2013 18:06:12 -0800 Subject: [PATCH] add .slice() tests for parent tracking/update --- index.js | 4 ---- test/slice.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 test/slice.js diff --git a/index.js b/index.js index 91bd85a..b39a624 100644 --- a/index.js +++ b/index.js @@ -381,8 +381,6 @@ function _hexSlice (buf, start, end) { return out } -// TODO: add test that modifying the new buffer slice will modify memory in the -// original buffer! Use code from: // http://nodejs.org/api/buffer.html#buffer_buf_slice_start_end Buffer.prototype.slice = function (start, end) { var len = this.length @@ -392,8 +390,6 @@ Buffer.prototype.slice = function (start, end) { if (browserSupport) { return augment(this.subarray(start, end)) } else { - // TODO: slicing works, with limitations (no parent tracking/update) - // https://github.com/feross/native-buffer-browserify/issues/9 var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { diff --git a/test/slice.js b/test/slice.js new file mode 100644 index 0000000..2959911 --- /dev/null +++ b/test/slice.js @@ -0,0 +1,32 @@ +var B = require('../index.js').Buffer +var test = require('tape') + +test('modifying buffer created by .slice() modifies original memory', function (t) { + var buf1 = new Buffer(26) + for (var i = 0 ; i < 26 ; i++) { + buf1[i] = i + 97 // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3) + t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') + + buf2[0] = '!'.charCodeAt(0) + t.equal(buf1.toString('ascii', 0, buf2.length), '!bc') + + t.end() +}) + +test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) { + var buf1 = new Buffer(26) + for (var i = 0 ; i < 26 ; i++) { + buf1[i] = i + 97 // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3) + t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') + + buf1[0] = '!'.charCodeAt(0) + t.equal(buf2.toString('ascii', 0, buf2.length), '!bc') + + t.end() +}) -- 2.34.1