Skip to content
This repository has been archived by the owner on Apr 5, 2018. It is now read-only.

safe-buffer #3

Merged
merged 2 commits into from
May 19, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ npm install --save string_decoder

This package is a mirror of the string_decoder implementation in Node-core.

Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v7.8.0/docs/api/).
Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v7.0.0/docs/api/).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you sure about this? Have you pulled from the right codebase?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope just misread an 8 as a 0, again


As of version 1.0.0 **string_decoder** uses semantic versioning.

Expand Down
10 changes: 1 addition & 9 deletions build/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,7 @@ module.exports['string_decoder.js'] = [

, [
/const Buffer = require\('buffer'\).Buffer;/
, 'var Buffer = require(\'buffer\').Buffer;\n' +
'var bufferShim = require(\'buffer-shims\');'
]

// allocUnsafe

, [
/Buffer\.((?:alloc)|(?:allocUnsafe)|(?:from))/g,
'bufferShim.$1'
, 'var Buffer = require(\'safe-buffer\').Buffer;\n'
]

// add Buffer.isEncoding where missing
Expand Down
3 changes: 1 addition & 2 deletions build/test-replacements.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module.exports.all = [

, [
/^('use strict';)$/m,
'$1\nconst bufferShim = require(\'buffer-shims\');'
'$1\nconst bufferShim = require(\'safe-buffer\').Buffer;'
]

]
Expand Down Expand Up @@ -60,4 +60,3 @@ module.exports['test-string-decoder.js'] = [
, ''
]
]

5 changes: 2 additions & 3 deletions lib/string_decoder.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

var Buffer = require('buffer').Buffer;
var bufferShim = require('buffer-shims');
var Buffer = require('safe-buffer').Buffer;

var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
Expand Down Expand Up @@ -78,7 +77,7 @@ function StringDecoder(encoding) {
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = bufferShim.allocUnsafe(nb);
this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "The string_decoder module from Node core",
"main": "lib/string_decoder.js",
"dependencies": {
"buffer-shims": "~1.0.0"
"safe-buffer": "^5.0.1"
},
"devDependencies": {
"babel-polyfill": "^6.23.0",
Expand Down
175 changes: 43 additions & 132 deletions test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ var child_process = require('child_process');
var stream = require('stream');
var util = require('util');
var Timer = process.binding('timer_wrap').Timer;
var execSync = require('child_process').execSync;

var testRoot = process.env.NODE_TEST_DIR ? fs.realpathSync(process.env.NODE_TEST_DIR) : __dirname;
var testRoot = process.env.NODE_TEST_DIR ? path.resolve(process.env.NODE_TEST_DIR) : __dirname;

exports.fixturesDir = path.join(__dirname, 'fixtures');
exports.testDir = __dirname;
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.tmpDirName = 'tmp';
// PORT should match the definition in test/testpy/__init__.py.
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
Expand All @@ -28,15 +28,14 @@ exports.isOSX = process.platform === 'darwin';
exports.enoughTestMem = os.totalmem() > 0x40000000; /* 1 Gb */

var cpus = os.cpus();
exports.enoughTestCpu = Array.isArray(cpus) && (cpus.length > 1 || cpus[0].speed > 999);
exports.enoughTestCpu = cpus.length > 1 || cpus[0].speed > 999;

exports.rootDir = exports.isWindows ? 'c:\\' : '/';
exports.buildType = process.config.target_defaults.default_configuration;

function rimrafSync(p) {
var st = void 0;
try {
st = fs.lstatSync(p);
var st = fs.lstatSync(p);
} catch (e) {
if (e.code === 'ENOENT') return;
}
Expand Down Expand Up @@ -147,8 +146,8 @@ Object.defineProperty(exports, 'opensslCli', { get: function () {

if (exports.isWindows) opensslCli += '.exe';

var opensslCmd = child_process.spawnSync(opensslCli, ['version']);
if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) {
var openssl_cmd = child_process.spawnSync(opensslCli, ['version']);
if (openssl_cmd.status !== 0 || openssl_cmd.error !== undefined) {
// openssl command cannot be executed
opensslCli = false;
}
Expand Down Expand Up @@ -176,6 +175,12 @@ if (exports.isWindows) {
exports.PIPE = exports.tmpDir + '/test.sock';
}

if (exports.isWindows) {
exports.faketimeCli = false;
} else {
exports.faketimeCli = path.join(__dirname, '..', 'tools', 'faketime', 'src', 'faketime');
}

var ifaces = os.networkInterfaces();
exports.hasIPv6 = Object.keys(ifaces).some(function (name) {
return (/lo/.test(name) && ifaces[name].some(function (info) {
Expand All @@ -184,27 +189,6 @@ exports.hasIPv6 = Object.keys(ifaces).some(function (name) {
);
});

/*
* Check that when running a test with
* `$node --abort-on-uncaught-exception $file child`
* the process aborts.
*/
exports.childShouldThrowAndAbort = function () {
var testCmd = '';
if (!exports.isWindows) {
// Do not create core files, as it can take a lot of disk space on
// continuous testing and developers' machines
testCmd += 'ulimit -c 0 && ';
}
testCmd += process.argv[0] + ' --abort-on-uncaught-exception ';
testCmd += process.argv[1] + ' child';
var child = child_process.exec(testCmd);
child.on('exit', function onExit(exitCode, signal) {
var errMsg = 'Test should have aborted ' + ('but instead exited with exit code ' + exitCode) + (' and signal ' + signal);
assert(exports.nodeProcessAborted(exitCode, signal), errMsg);
});
};

exports.ddCommand = function (filename, kilobytes) {
if (exports.isWindows) {
var p = path.resolve(exports.fixturesDir, 'create-file.js');
Expand All @@ -214,6 +198,26 @@ exports.ddCommand = function (filename, kilobytes) {
}
};

exports.spawnCat = function (options) {
var spawn = require('child_process').spawn;

if (exports.isWindows) {
return spawn('more', [], options);
} else {
return spawn('cat', [], options);
}
};

exports.spawnSyncCat = function (options) {
var spawnSync = require('child_process').spawnSync;

if (exports.isWindows) {
return spawnSync('more', [], options);
} else {
return spawnSync('cat', [], options);
}
};

exports.spawnPwd = function (options) {
var spawn = require('child_process').spawn;

Expand All @@ -237,8 +241,6 @@ exports.spawnSyncPwd = function (options) {
exports.platformTimeout = function (ms) {
if (process.config.target_defaults.default_configuration === 'Debug') ms = 2 * ms;

if (global.__coverage__) ms = 4 * ms;

if (exports.isAix) return 2 * ms; // default localhost speed is slower on AIX

if (process.arch !== 'arm') return ms;
Expand All @@ -252,8 +254,8 @@ exports.platformTimeout = function (ms) {
return ms; // ARMv8+
};

var knownGlobals = [Buffer, clearImmediate, clearInterval, clearTimeout, console, constructor, // Enumerable in V8 3.21.
global, process, setImmediate, setInterval, setTimeout];
var knownGlobals = [setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, clearImmediate, console, constructor, // Enumerable in V8 3.21.
Buffer, process, global];

if (global.gc) {
knownGlobals.push(global.gc);
Expand Down Expand Up @@ -333,14 +335,8 @@ function leakedGlobals() {
var leaked = [];

for (var val in global) {
if (!knownGlobals.includes(global[val])) leaked.push(val);
}if (global.__coverage__) {
return leaked.filter(function (varname) {
return !/^(cov_|__cov)/.test(varname);
});
} else {
return leaked;
}
if (-1 === knownGlobals.indexOf(global[val])) leaked.push(val);
}return leaked;
}
exports.leakedGlobals = leakedGlobals;

Expand All @@ -351,7 +347,8 @@ process.on('exit', function () {
if (!exports.globalCheck) return;
var leaked = leakedGlobals();
if (leaked.length > 0) {
fail('Unexpected global(s) found: ' + leaked.join(', '));
console.error('Unknown globals: %s', leaked);
assert.ok(false, 'Unknown global found');
}
});

Expand All @@ -373,7 +370,7 @@ function runCallChecks(exitCode) {
}

exports.mustCall = function (fn, expected) {
if (expected === undefined) expected = 1;else if (typeof expected !== 'number') throw new TypeError('Invalid expected value: ' + expected);
if (typeof expected !== 'number') expected = 1;

var context = {
expected: expected,
Expand Down Expand Up @@ -410,42 +407,8 @@ exports.fileExists = function (pathname) {
}
};

exports.canCreateSymLink = function () {
// On Windows, creating symlinks requires admin privileges.
// We'll only try to run symlink test if we have enough privileges.
// On other platforms, creating symlinks shouldn't need admin privileges
if (exports.isWindows) {
// whoami.exe needs to be the one from System32
// If unix tools are in the path, they can shadow the one we want,
// so use the full path while executing whoami
var whoamiPath = path.join(process.env['SystemRoot'], 'System32', 'whoami.exe');

var err = false;
var output = '';

try {
output = execSync(whoamiPath + ' /priv', { timout: 1000 });
} catch (e) {
err = true;
} finally {
if (err || !output.includes('SeCreateSymbolicLinkPrivilege')) {
return false;
}
}
}

return true;
};

function fail(msg) {
exports.fail = function (msg) {
assert.fail(null, null, msg);
}
exports.fail = fail;

exports.mustNotCall = function (msg) {
return function mustNotCall() {
fail(msg || 'function should not have been called');
};
};

exports.skip = function (msg) {
Expand Down Expand Up @@ -498,9 +461,9 @@ exports.nodeProcessAborted = function nodeProcessAborted(exitCode, signal) {
// one of them (exit code or signal) needs to be set to one of
// the expected exit codes or signals.
if (signal !== null) {
return expectedSignals.includes(signal);
return expectedSignals.indexOf(signal) > -1;
} else {
return expectedExitCodes.includes(exitCode);
return expectedExitCodes.indexOf(exitCode) > -1;
}
};

Expand Down Expand Up @@ -528,56 +491,4 @@ exports.expectWarning = function (name, expected) {
// get each message only once.
expected.splice(expected.indexOf(warning.message), 1);
}, expected.length));
};

Object.defineProperty(exports, 'hasIntl', {
get: function () {
return process.binding('config').hasIntl;
}
});

// https://github.com/w3c/testharness.js/blob/master/testharness.js
exports.WPT = {
test: function (fn, desc) {
try {
fn();
} catch (err) {
if (err instanceof Error) err.message = 'In ' + desc + ':\n ' + err.message;
throw err;
}
},
assert_equals: assert.strictEqual,
assert_true: function (value, message) {
return assert.strictEqual(value, true, message);
},
assert_false: function (value, message) {
return assert.strictEqual(value, false, message);
},
assert_throws: function (code, func, desc) {
assert.throws(func, function (err) {
return typeof err === 'object' && 'name' in err && err.name === code.name;
}, desc);
},
assert_array_equals: assert.deepStrictEqual,
assert_unreached: function (desc) {
assert.fail(undefined, undefined, 'Reached unreachable code: ' + desc);
}
};

// Useful for testing expected internal/error objects
exports.expectsError = function expectsError(_ref) {
var code = _ref.code,
type = _ref.type,
message = _ref.message;

return function (error) {
assert.strictEqual(error.code, code);
if (type !== undefined) assert(error instanceof type, error + ' is not the expected type ' + type);
if (message instanceof RegExp) {
assert(message.test(error.message), error.message + ' does not match ' + message);
} else if (typeof message === 'string') {
assert.strictEqual(error.message, message);
}
return true;
};
};
12 changes: 6 additions & 6 deletions test/parallel/test-string-decoder-end.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

var bufferShim = require('buffer-shims');
var bufferShim = require('safe-buffer').Buffer;
// verify that the string decoder works getting 1 byte at a time,
// the whole buffer at once, and that both match the .toString(enc)
// result of the entire buffer.
Expand All @@ -16,7 +16,7 @@ var bufs = ['☃💩', 'asdf'].map(function (b) {

// also test just arbitrary bytes from 0-15.
for (var i = 1; i <= 16; i++) {
var bytes = '.'.repeat(i - 1).split('.').map(function (_, j) {
var bytes = new Array(i).join('.').split('.').map(function (_, j) {
return j + 0x78;
});
bufs.push(bufferShim.from(bytes));
Expand All @@ -38,8 +38,8 @@ function testBuf(encoding, buf) {
// write one byte at a time.
var s = new SD(encoding);
var res1 = '';
for (var _i = 0; _i < buf.length; _i++) {
res1 += s.write(buf.slice(_i, _i + 1));
for (var i = 0; i < buf.length; i++) {
res1 += s.write(buf.slice(i, i + 1));
}
res1 += s.end();

Expand All @@ -55,6 +55,6 @@ function testBuf(encoding, buf) {
console.log('expect=%j', res3);
console.log('res1=%j', res1);
console.log('res2=%j', res2);
assert.strictEqual(res1, res3, 'one byte at a time should match toString');
assert.strictEqual(res2, res3, 'all bytes at once should match toString');
assert.equal(res1, res3, 'one byte at a time should match toString');
assert.equal(res2, res3, 'all bytes at once should match toString');
}
Loading