Browse Source

buffer: propagate originating parent

When creating a slice, make sure to propagate the originating parent.
This is to prevent a buf.parent.parent.(etc) scenario.

Also speed up the constructor by preventing lookup of non-existant
properties by setting them beforehand in the prototype. (see
https://github.com/joyent/node/commit/7ce5a31#commitcomment-3332779)
Trevor Norris 12 years ago
parent
commit
b8ce1da74d
  1. 8
      lib/buffer.js
  2. 16
      test/simple/test-buffer.js

8
lib/buffer.js

@ -197,6 +197,11 @@ Buffer.dispose = function(obj) {
};
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined;
Buffer.prototype.parent = undefined;
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
@ -387,7 +392,8 @@ Buffer.prototype.slice = function(start, end) {
end = start;
var buf = new Buffer();
buf.parent = sliceOnto(this, buf, start, end);
sliceOnto(this, buf, start, end);
buf.parent = this.parent === undefined ? this : this.parent;
buf.length = end - start;
return buf;

16
test/simple/test-buffer.js

@ -23,6 +23,7 @@ var common = require('../common');
var assert = require('assert');
var Buffer = require('buffer').Buffer;
var SlowBuffer = require('buffer').SlowBuffer;
// counter to ensure unique value is always copied
var cntr = 0;
@ -271,6 +272,21 @@ for (var j = 0; j < 100; j++) {
}
// make sure only top level parent propagates from allocPool
var b = new Buffer(5);
var c = b.slice(0, 4);
var d = c.slice(0, 2);
assert.equal(b.parent, c.parent);
assert.equal(b.parent, d.parent);
// also from a non-pooled instance
var b = new SlowBuffer(5);
var c = b.slice(0, 4);
var d = c.slice(0, 2);
assert.equal(b, c.parent);
assert.equal(b, d.parent);
// Bug regression test
var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語

Loading…
Cancel
Save