From b8ce1da74d6ca01a7da2921b5911aa05aeaa6582 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Mon, 8 Jul 2013 20:58:39 -0700 Subject: [PATCH] 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) --- lib/buffer.js | 8 +++++++- test/simple/test-buffer.js | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index 81ecf790b17..a34d3199711 100644 --- a/lib/buffer.js +++ b/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; diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 6975c8e4e58..f186af9ae68 100644 --- a/test/simple/test-buffer.js +++ b/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'; // ö日本語