}
};
-
// slice(start, end)
-Buffer.prototype.slice = function(start, end) {
- if (end === undefined) end = this.length;
-
- if (end > this.length) {
- throw new Error('oob');
- }
- if (start > end) {
- throw new Error('oob');
- }
+function clamp(index, len, defaultValue) {
+ if (typeof index !== 'number') return defaultValue;
+ index = ~~index; // Coerce to integer.
+ if (index >= len) return len;
+ if (index >= 0) return index;
+ index += len;
+ if (index >= 0) return index;
+ return 0;
+}
+Buffer.prototype.slice = function(start, end) {
+ var len = this.length;
+ start = clamp(start, len, 0);
+ end = clamp(end, len, len);
return new Buffer(this, end - start, +start);
};
t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo');
t.end();
});
+
+test('buffer.slice out of range', function (t) {
+ t.plan(2);
+ t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo');
+ t.equal((new B('hallo')).slice(10, 2).toString(), '');
+ t.end();
+});