borrow clamp function from node since buffer.slice in v0.8 doesn't have such logic.

This commit is contained in:
Chris Talkington 2014-01-05 17:48:14 -06:00
parent 645aeb9538
commit 4d31ce9d77
2 changed files with 24 additions and 4 deletions

View file

@ -2,6 +2,16 @@ var ZEROS = '0000000000000000000';
var ZERO_OFFSET = '0'.charCodeAt(0); var ZERO_OFFSET = '0'.charCodeAt(0);
var USTAR = 'ustar00'; var USTAR = 'ustar00';
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;
}
var toType = function(flag) { var toType = function(flag) {
switch (flag) { switch (flag) {
case 0: case 0:
@ -19,7 +29,7 @@ var toType = function(flag) {
case 6: case 6:
return 'fifo'; return 'fifo';
case 7: case 7:
return 'contiguous-file' return 'contiguous-file';
case 72: case 72:
return 'pax-header'; return 'pax-header';
} }
@ -78,7 +88,7 @@ var encodeOct = function(val, n) {
}; };
var decodeOct = function(val, offset) { var decodeOct = function(val, offset) {
return parseInt(val.slice(offset, indexOf(val, 32, offset)).toString(), 8); return parseInt(val.slice(offset, clamp(indexOf(val, 32, offset), val.length, val.length)).toString(), 8);
}; };
var decodeStr = function(val, offset) { var decodeStr = function(val, offset) {

View file

@ -4,6 +4,16 @@ var fixtures = require('./fixtures');
var concat = require('concat-stream'); var concat = require('concat-stream');
var fs = require('fs'); var fs = require('fs');
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;
}
test('one-file', function(t) { test('one-file', function(t) {
t.plan(3); t.plan(3);
@ -76,7 +86,7 @@ test('chunked-one-file', function(t) {
var b = fs.readFileSync(fixtures.ONE_FILE_TAR); var b = fs.readFileSync(fixtures.ONE_FILE_TAR);
for (var i = 0; i < b.length; i += 321) { for (var i = 0; i < b.length; i += 321) {
extract.write(b.slice(i, i+321)); extract.write(b.slice(i, clamp(i+321, b.length, b.length)));
} }
extract.end(); extract.end();
}); });
@ -203,7 +213,7 @@ test('chunked-multi-file', function(t) {
var b = fs.readFileSync(fixtures.MULTI_FILE_TAR); var b = fs.readFileSync(fixtures.MULTI_FILE_TAR);
for (var i = 0; i < b.length; i += 321) { for (var i = 0; i < b.length; i += 321) {
extract.write(b.slice(i, i+321)); extract.write(b.slice(i, clamp(i+321, b.length, b.length)));
} }
extract.end(); extract.end();
}); });