Browse Source

buffer: add .from(), .alloc() and .allocUnsafe()

Several changes:

* Soft-Deprecate Buffer() constructors
* Add `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
* Add `--zero-fill-buffers` command line option
* Add byteOffset and length to `new Buffer(arrayBuffer)` constructor
* buffer.fill('') previously had no effect, now zero-fills
* Update the docs

PR-URL: https://github.com/nodejs/node/pull/4682
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
process-exit-stdio-flushing
James M Snell 9 years ago
parent
commit
85ab4a5f12
  1. 2
      benchmark/buffers/buffer-base64-decode.js
  2. 2
      benchmark/buffers/buffer-base64-encode.js
  3. 2
      benchmark/buffers/buffer-bytelength.js
  4. 8
      benchmark/buffers/buffer-compare.js
  5. 61
      benchmark/buffers/buffer-creation.js
  6. 4
      benchmark/buffers/buffer-indexof.js
  7. 2
      benchmark/buffers/buffer-slice.js
  8. 2
      benchmark/buffers/buffer-tostring.js
  9. 4
      benchmark/buffers/buffer_zero.js
  10. 4
      benchmark/crypto/aes-gcm-throughput.js
  11. 3
      benchmark/crypto/cipher-stream.js
  12. 5
      benchmark/crypto/hash-stream-creation.js
  13. 3
      benchmark/crypto/hash-stream-throughput.js
  14. 3
      benchmark/crypto/rsa-encrypt-decrypt-throughput.js
  15. 3
      benchmark/crypto/rsa-sign-verify-throughput.js
  16. 2
      benchmark/dgram/array-vs-concat.js
  17. 2
      benchmark/dgram/multi-buffer.js
  18. 2
      benchmark/dgram/offset-length.js
  19. 2
      benchmark/dgram/single-buffer.js
  20. 3
      benchmark/fs-write-stream-throughput.js
  21. 2
      benchmark/fs/read-stream-throughput.js
  22. 3
      benchmark/fs/readfile.js
  23. 3
      benchmark/fs/write-stream-throughput.js
  24. 2
      benchmark/http/bench-parser.js
  25. 3
      benchmark/http/chunked.js
  26. 3
      benchmark/http/client-request-body.js
  27. 3
      benchmark/http/end-vs-write-end.js
  28. 2
      benchmark/http_simple.js
  29. 2
      benchmark/http_simple_auto.js
  30. 3
      benchmark/net/net-c2s-cork.js
  31. 3
      benchmark/net/net-c2s.js
  32. 3
      benchmark/net/net-pipe.js
  33. 3
      benchmark/net/net-s2c.js
  34. 3
      benchmark/net/tcp-raw-c2s.js
  35. 3
      benchmark/net/tcp-raw-pipe.js
  36. 3
      benchmark/net/tcp-raw-s2c.js
  37. 10
      benchmark/string_decoder/string-decoder.js
  38. 4
      benchmark/tls/throughput.js
  39. 533
      doc/api/buffer.markdown
  40. 3
      doc/node.1
  41. 2
      lib/_debugger.js
  42. 2
      lib/_http_client.js
  43. 2
      lib/_http_outgoing.js
  44. 4
      lib/_stream_readable.js
  45. 2
      lib/_stream_writable.js
  46. 2
      lib/_tls_legacy.js
  47. 4
      lib/_tls_wrap.js
  48. 2
      lib/assert.js
  49. 138
      lib/buffer.js
  50. 2
      lib/child_process.js
  51. 2
      lib/crypto.js
  52. 6
      lib/dgram.js
  53. 22
      lib/fs.js
  54. 2
      lib/internal/v8_prof_polyfill.js
  55. 2
      lib/net.js
  56. 2
      lib/querystring.js
  57. 2
      lib/string_decoder.js
  58. 4
      lib/tls.js
  59. 10
      lib/zlib.js
  60. 8
      src/node.cc
  61. 27
      src/node_buffer.cc
  62. 3
      src/node_buffer.h
  63. 2
      test/disabled/test-debug-brk-file.js
  64. 3
      test/disabled/test-dgram-send-error.js
  65. 5
      test/disabled/test-fs-largefile.js
  66. 2
      test/disabled/test-sendfd.js
  67. 2
      test/fixtures/GH-892-request.js
  68. 2
      test/fixtures/print-chars-from-buffer.js
  69. 8
      test/internet/test-dgram-broadcast-multi-process.js
  70. 8
      test/internet/test-dgram-multicast-multi-process.js
  71. 2
      test/internet/test-dgram-send-cb-quelches-error.js
  72. 2
      test/parallel/test-async-wrap-check-providers.js
  73. 1442
      test/parallel/test-buffer-alloc.js
  74. 62
      test/parallel/test-buffer-arraybuffer.js
  75. 4
      test/parallel/test-buffer-ascii.js
  76. 4
      test/parallel/test-buffer-bytelength.js
  77. 8
      test/parallel/test-buffer-concat.js
  78. 6
      test/parallel/test-buffer-fakes.js
  79. 14
      test/parallel/test-buffer-fill.js
  80. 72
      test/parallel/test-buffer-includes.js
  81. 82
      test/parallel/test-buffer-indexof.js
  82. 8
      test/parallel/test-buffer-inspect.js
  83. 2
      test/parallel/test-buffer-iterator.js
  84. 14
      test/parallel/test-buffer-safe-unsafe.js
  85. 11
      test/parallel/test-buffer-slow.js
  86. 32
      test/parallel/test-buffer-zero-fill-cli.js
  87. 2
      test/parallel/test-buffer-zero-fill-reset.js
  88. 89
      test/parallel/test-buffer.js
  89. 2
      test/parallel/test-child-process-fork-dgram.js
  90. 8
      test/parallel/test-child-process-spawnsync-input.js
  91. 2
      test/parallel/test-child-process-spawnsync-maxbuf.js
  92. 6
      test/parallel/test-child-process-stdio-big-write-end.js
  93. 2
      test/parallel/test-cluster-dgram-1.js
  94. 2
      test/parallel/test-cluster-dgram-2.js
  95. 26
      test/parallel/test-crypto-authenticated.js
  96. 74
      test/parallel/test-crypto-binary-default.js
  97. 4
      test/parallel/test-crypto-cipher-decipher.js
  98. 8
      test/parallel/test-crypto-cipheriv-decipheriv.js
  99. 3
      test/parallel/test-crypto-dh-odd-key.js
  100. 4
      test/parallel/test-crypto-dh.js

2
benchmark/buffers/buffer-base64-decode.js

@ -8,7 +8,7 @@ function main(conf) {
const s = 'abcd'.repeat(8 << 20); const s = 'abcd'.repeat(8 << 20);
s.match(/./); // Flatten string. s.match(/./); // Flatten string.
assert.equal(s.length % 4, 0); assert.equal(s.length % 4, 0);
const b = Buffer(s.length / 4 * 3); const b = Buffer.allocUnsafe(s.length / 4 * 3);
b.write(s, 0, s.length, 'base64'); b.write(s, 0, s.length, 'base64');
bench.start(); bench.start();
for (var i = 0; i < 32; i += 1) b.base64Write(s, 0, s.length); for (var i = 0; i < 32; i += 1) b.base64Write(s, 0, s.length);

2
benchmark/buffers/buffer-base64-encode.js

@ -5,7 +5,7 @@ var bench = common.createBenchmark(main, {});
function main(conf) { function main(conf) {
var N = 64 * 1024 * 1024; var N = 64 * 1024 * 1024;
var b = Buffer(N); var b = Buffer.allocUnsafe(N);
var s = ''; var s = '';
var i; var i;
for (i = 0; i < 256; ++i) s += String.fromCharCode(i); for (i = 0; i < 256; ++i) s += String.fromCharCode(i);

2
benchmark/buffers/buffer-bytelength.js

@ -28,7 +28,7 @@ function main(conf) {
strings.push(data); strings.push(data);
} else if (encoding === 'base64') { } else if (encoding === 'base64') {
// Base64 strings will be much longer than their UTF8 counterparts // Base64 strings will be much longer than their UTF8 counterparts
strings.push(new Buffer(data, 'utf8').toString('base64')); strings.push(Buffer.from(data, 'utf8').toString('base64'));
} }
} }

8
benchmark/buffers/buffer-compare.js

@ -7,10 +7,10 @@ var bench = common.createBenchmark(main, {
}); });
function main(conf) { function main(conf) {
var iter = (conf.millions >>> 0) * 1e6; const iter = (conf.millions >>> 0) * 1e6;
var size = (conf.size >>> 0); const size = (conf.size >>> 0);
var b0 = new Buffer(size).fill('a'); const b0 = Buffer.alloc(size, 'a');
var b1 = new Buffer(size).fill('a'); const b1 = Buffer.alloc(size, 'a');
b1[size - 1] = 'b'.charCodeAt(0); b1[size - 1] = 'b'.charCodeAt(0);

61
benchmark/buffers/buffer-creation.js

@ -1,20 +1,59 @@
'use strict'; 'use strict';
const SlowBuffer = require('buffer').SlowBuffer; const SlowBuffer = require('buffer').SlowBuffer;
var common = require('../common.js'); const common = require('../common.js');
var bench = common.createBenchmark(main, { const assert = require('assert');
type: ['fast', 'slow'], const bench = common.createBenchmark(main, {
len: [10, 1024], type: [
'fast-alloc',
'fast-alloc-fill',
'fast-allocUnsafe',
'slow',
'buffer()'],
len: [10, 1024, 2048, 4096, 8192],
n: [1024] n: [1024]
}); });
function main(conf) { function main(conf) {
var len = +conf.len; const len = +conf.len;
var n = +conf.n; const n = +conf.n;
var clazz = conf.type === 'fast' ? Buffer : SlowBuffer; switch (conf.type) {
bench.start(); case 'fast-alloc':
for (var i = 0; i < n * 1024; i++) { bench.start();
new clazz(len); for (let i = 0; i < n * 1024; i++) {
Buffer.alloc(len);
}
bench.end(n);
break;
case 'fast-alloc-fill':
bench.start();
for (let i = 0; i < n * 1024; i++) {
Buffer.alloc(len, 0);
}
bench.end(n);
break;
case 'fast-allocUnsafe':
bench.start();
for (let i = 0; i < n * 1024; i++) {
Buffer.allocUnsafe(len);
}
bench.end(n);
break;
case 'slow':
bench.start();
for (let i = 0; i < n * 1024; i++) {
SlowBuffer(len);
}
bench.end(n);
break;
case 'buffer()':
bench.start();
for (let i = 0; i < n * 1024; i++) {
Buffer(len);
}
bench.end(n);
break;
default:
assert.fail(null, null, 'Should not get here');
} }
bench.end(n);
} }

4
benchmark/buffers/buffer-indexof.js

@ -27,11 +27,11 @@ function main(conf) {
} }
if (encoding === 'ucs2') { if (encoding === 'ucs2') {
aliceBuffer = new Buffer(aliceBuffer.toString(), encoding); aliceBuffer = Buffer.from(aliceBuffer.toString(), encoding);
} }
if (conf.type === 'buffer') { if (conf.type === 'buffer') {
search = new Buffer(new Buffer(search).toString(), encoding); search = Buffer.from(Buffer.from(search).toString(), encoding);
} }
bench.start(); bench.start();

2
benchmark/buffers/buffer-slice.js

@ -7,7 +7,7 @@ var bench = common.createBenchmark(main, {
n: [1024] n: [1024]
}); });
var buf = new Buffer(1024); var buf = Buffer.allocUnsafe(1024);
var slowBuf = new SlowBuffer(1024); var slowBuf = new SlowBuffer(1024);
function main(conf) { function main(conf) {

2
benchmark/buffers/buffer-tostring.js

@ -12,7 +12,7 @@ function main(conf) {
const arg = conf.arg === 'true'; const arg = conf.arg === 'true';
const len = conf.len | 0; const len = conf.len | 0;
const n = conf.n | 0; const n = conf.n | 0;
const buf = Buffer(len).fill(42); const buf = Buffer.alloc(len, 42);
var i; var i;
bench.start(); bench.start();

4
benchmark/buffers/buffer_zero.js

@ -6,13 +6,13 @@ const bench = common.createBenchmark(main, {
n: [1024] n: [1024]
}); });
const zero = new Buffer(0); const zero = Buffer.alloc(0);
function main(conf) { function main(conf) {
var n = +conf.n; var n = +conf.n;
bench.start(); bench.start();
for (let i = 0; i < n * 1024; i++) { for (let i = 0; i < n * 1024; i++) {
new Buffer(zero); Buffer.from(zero);
} }
bench.end(n); bench.end(n);
} }

4
benchmark/crypto/aes-gcm-throughput.js

@ -9,10 +9,10 @@ var bench = common.createBenchmark(main, {
}); });
function main(conf) { function main(conf) {
var message = (new Buffer(conf.len)).fill('b'); var message = Buffer.alloc(conf.len, 'b');
var key = crypto.randomBytes(keylen[conf.cipher]); var key = crypto.randomBytes(keylen[conf.cipher]);
var iv = crypto.randomBytes(12); var iv = crypto.randomBytes(12);
var associate_data = (new Buffer(16)).fill('z'); var associate_data = Buffer.alloc(16, 'z');
bench.start(); bench.start();
AEAD_Bench(conf.cipher, message, associate_data, key, iv, conf.n, conf.len); AEAD_Bench(conf.cipher, message, associate_data, key, iv, conf.n, conf.len);
} }

3
benchmark/crypto/cipher-stream.js

@ -48,8 +48,7 @@ function main(conf) {
encoding = 'utf8'; encoding = 'utf8';
break; break;
case 'buf': case 'buf':
message = new Buffer(conf.len); message = Buffer.alloc(conf.len, 'b');
message.fill('b');
break; break;
default: default:
throw new Error('unknown message type: ' + conf.type); throw new Error('unknown message type: ' + conf.type);

5
benchmark/crypto/hash-stream-creation.js

@ -33,8 +33,7 @@ function main(conf) {
encoding = 'utf8'; encoding = 'utf8';
break; break;
case 'buf': case 'buf':
message = new Buffer(conf.len); message = Buffer.alloc(conf.len, 'b');
message.fill('b');
break; break;
default: default:
throw new Error('unknown message type: ' + conf.type); throw new Error('unknown message type: ' + conf.type);
@ -58,7 +57,7 @@ function legacyWrite(algo, message, encoding, writes, len, outEnc) {
// include buffer creation costs for older versions // include buffer creation costs for older versions
if (outEnc === 'buffer' && typeof res === 'string') if (outEnc === 'buffer' && typeof res === 'string')
res = new Buffer(res, 'binary'); res = Buffer.from(res, 'binary');
} }
bench.end(gbits); bench.end(gbits);

3
benchmark/crypto/hash-stream-throughput.js

@ -32,8 +32,7 @@ function main(conf) {
encoding = 'utf8'; encoding = 'utf8';
break; break;
case 'buf': case 'buf':
message = new Buffer(conf.len); message = Buffer.alloc(conf.len, 'b');
message.fill('b');
break; break;
default: default:
throw new Error('unknown message type: ' + conf.type); throw new Error('unknown message type: ' + conf.type);

3
benchmark/crypto/rsa-encrypt-decrypt-throughput.js

@ -23,8 +23,7 @@ var bench = common.createBenchmark(main, {
}); });
function main(conf) { function main(conf) {
var message = (new Buffer(conf.len)).fill('b'); var message = Buffer.alloc(conf.len, 'b');
bench.start(); bench.start();
StreamWrite(conf.algo, conf.keylen, message, conf.n, conf.len); StreamWrite(conf.algo, conf.keylen, message, conf.n, conf.len);
} }

3
benchmark/crypto/rsa-sign-verify-throughput.js

@ -24,8 +24,7 @@ var bench = common.createBenchmark(main, {
}); });
function main(conf) { function main(conf) {
var message = (new Buffer(conf.len)).fill('b'); var message = Buffer.alloc(conf.len, 'b');
bench.start(); bench.start();
StreamWrite(conf.algo, conf.keylen, message, conf.writes, conf.len); StreamWrite(conf.algo, conf.keylen, message, conf.writes, conf.len);
} }

2
benchmark/dgram/array-vs-concat.js

@ -31,7 +31,7 @@ function main(conf) {
chunk = []; chunk = [];
for (var i = 0; i < chunks; i++) { for (var i = 0; i < chunks; i++) {
chunk.push(new Buffer(Math.round(len / chunks))); chunk.push(Buffer.allocUnsafe(Math.round(len / chunks)));
} }
server(); server();

2
benchmark/dgram/multi-buffer.js

@ -31,7 +31,7 @@ function main(conf) {
chunk = []; chunk = [];
for (var i = 0; i < chunks; i++) { for (var i = 0; i < chunks; i++) {
chunk.push(new Buffer(Math.round(len / chunks))); chunk.push(Buffer.allocUnsafe(Math.round(len / chunks)));
} }
server(); server();

2
benchmark/dgram/offset-length.js

@ -25,7 +25,7 @@ function main(conf) {
len = +conf.len; len = +conf.len;
num = +conf.num; num = +conf.num;
type = conf.type; type = conf.type;
chunk = new Buffer(len); chunk = Buffer.allocUnsafe(len);
server(); server();
} }

2
benchmark/dgram/single-buffer.js

@ -25,7 +25,7 @@ function main(conf) {
len = +conf.len; len = +conf.len;
num = +conf.num; num = +conf.num;
type = conf.type; type = conf.type;
chunk = new Buffer(len); chunk = Buffer.allocUnsafe(len);
server(); server();
} }

3
benchmark/fs-write-stream-throughput.js

@ -45,8 +45,7 @@ function runTest(dur, size, type) {
chunk = new Array(size + 1).join('a'); chunk = new Array(size + 1).join('a');
break; break;
case 'buffer': case 'buffer':
chunk = new Buffer(size); chunk = Buffer.alloc(size, 'a');
chunk.fill('a');
break; break;
} }

2
benchmark/fs/read-stream-throughput.js

@ -60,7 +60,7 @@ function runTest() {
} }
function makeFile() { function makeFile() {
var buf = new Buffer(filesize / 1024); var buf = Buffer.allocUnsafe(filesize / 1024);
if (encoding === 'utf8') { if (encoding === 'utf8') {
// ü // ü
for (var i = 0; i < buf.length; i++) { for (var i = 0; i < buf.length; i++) {

3
benchmark/fs/readfile.js

@ -17,8 +17,7 @@ var bench = common.createBenchmark(main, {
function main(conf) { function main(conf) {
var len = +conf.len; var len = +conf.len;
try { fs.unlinkSync(filename); } catch (e) {} try { fs.unlinkSync(filename); } catch (e) {}
var data = new Buffer(len); var data = Buffer.alloc(len, 'x');
data.fill('x');
fs.writeFileSync(filename, data); fs.writeFileSync(filename, data);
data = null; data = null;

3
benchmark/fs/write-stream-throughput.js

@ -21,8 +21,7 @@ function main(conf) {
var chunk; var chunk;
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(size); chunk = Buffer.alloc(size, 'b');
chunk.fill('b');
break; break;
case 'asc': case 'asc':
chunk = new Array(size + 1).join('a'); chunk = new Array(size + 1).join('a');

2
benchmark/http/bench-parser.js

@ -25,7 +25,7 @@ function main(conf) {
} }
header += CRLF; header += CRLF;
processHeader(new Buffer(header), n); processHeader(Buffer.from(header), n);
} }

3
benchmark/http/chunked.js

@ -18,8 +18,7 @@ var bench = common.createBenchmark(main, {
function main(conf) { function main(conf) {
const http = require('http'); const http = require('http');
var chunk = new Buffer(conf.size); var chunk = Buffer.alloc(conf.size, '8');
chunk.fill('8');
var args = ['-d', '10s', '-t', 8, '-c', conf.c]; var args = ['-d', '10s', '-t', 8, '-c', conf.c];

3
benchmark/http/client-request-body.js

@ -19,8 +19,7 @@ function main(conf) {
var chunk; var chunk;
switch (conf.type) { switch (conf.type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
encoding = 'utf8'; encoding = 'utf8';

3
benchmark/http/end-vs-write-end.js

@ -23,8 +23,7 @@ function main(conf) {
var len = conf.kb * 1024; var len = conf.kb * 1024;
switch (conf.type) { switch (conf.type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
chunk = new Array(len / 2 + 1).join('ü'); chunk = new Array(len / 2 + 1).join('ü');

2
benchmark/http_simple.js

@ -51,7 +51,7 @@ var server = module.exports = http.createServer(function(req, res) {
if (n <= 0) if (n <= 0)
throw new Error('buffer called with n <= 0'); throw new Error('buffer called with n <= 0');
if (storedBuffer[n] === undefined) { if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n); storedBuffer[n] = Buffer.allocUnsafe(n);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
storedBuffer[n][i] = 'C'.charCodeAt(0); storedBuffer[n][i] = 'C'.charCodeAt(0);
} }

2
benchmark/http_simple_auto.js

@ -47,7 +47,7 @@ var server = http.createServer(function(req, res) {
n = parseInt(arg, 10); n = parseInt(arg, 10);
if (n <= 0) throw new Error('bytes called with n <= 0'); if (n <= 0) throw new Error('bytes called with n <= 0');
if (storedBuffer[n] === undefined) { if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n); storedBuffer[n] = Buffer.allocUnsafe(n);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
storedBuffer[n][i] = 'C'.charCodeAt(0); storedBuffer[n][i] = 'C'.charCodeAt(0);
} }

3
benchmark/net/net-c2s-cork.js

@ -23,8 +23,7 @@ function main(conf) {
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
encoding = 'utf8'; encoding = 'utf8';

3
benchmark/net/net-c2s.js

@ -23,8 +23,7 @@ function main(conf) {
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
encoding = 'utf8'; encoding = 'utf8';

3
benchmark/net/net-pipe.js

@ -23,8 +23,7 @@ function main(conf) {
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
encoding = 'utf8'; encoding = 'utf8';

3
benchmark/net/net-s2c.js

@ -23,8 +23,7 @@ function main(conf) {
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
encoding = 'utf8'; encoding = 'utf8';

3
benchmark/net/tcp-raw-c2s.js

@ -79,8 +79,7 @@ function client() {
var chunk; var chunk;
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
chunk = new Array(len / 2 + 1).join('ü'); chunk = new Array(len / 2 + 1).join('ü');

3
benchmark/net/tcp-raw-pipe.js

@ -77,8 +77,7 @@ function client() {
var chunk; var chunk;
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
chunk = new Array(len / 2 + 1).join('ü'); chunk = new Array(len / 2 + 1).join('ü');

3
benchmark/net/tcp-raw-s2c.js

@ -51,8 +51,7 @@ function server() {
var chunk; var chunk;
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(len); chunk = Buffer.alloc(len, 'x');
chunk.fill('x');
break; break;
case 'utf': case 'utf':
chunk = new Array(len / 2 + 1).join('ü'); chunk = new Array(len / 2 + 1).join('ü');

10
benchmark/string_decoder/string-decoder.js

@ -9,7 +9,7 @@ var bench = common.createBenchmark(main, {
n: [25e4] n: [25e4]
}); });
var UTF_ALPHA = 'Blåbærsyltetøy'; var UTF_ALPHA = 'Blåbærsyltetøy';
var ASC_ALPHA = 'Blueberry jam'; var ASC_ALPHA = 'Blueberry jam';
function main(conf) { function main(conf) {
@ -35,18 +35,18 @@ function main(conf) {
for (i = 0; i < inLen; ++i) { for (i = 0; i < inLen; ++i) {
if (i > 0 && (i % chunkLen) === 0 && !isBase64) { if (i > 0 && (i % chunkLen) === 0 && !isBase64) {
chunks.push(new Buffer(str, encoding)); chunks.push(Buffer.from(str, encoding));
str = ''; str = '';
} }
str += alpha[i % alpha.length]; str += alpha[i % alpha.length];
} }
if (str.length > 0 && !isBase64) if (str.length > 0 && !isBase64)
chunks.push(new Buffer(str, encoding)); chunks.push(Buffer.from(str, encoding));
if (isBase64) { if (isBase64) {
str = new Buffer(str, 'utf8').toString('base64'); str = Buffer.from(str, 'utf8').toString('base64');
while (str.length > 0) { while (str.length > 0) {
var len = Math.min(chunkLen, str.length); var len = Math.min(chunkLen, str.length);
chunks.push(new Buffer(str.substring(0, len), 'utf8')); chunks.push(Buffer.from(str.substring(0, len), 'utf8'));
str = str.substring(len); str = str.substring(len);
} }
} }

4
benchmark/tls/throughput.js

@ -23,8 +23,7 @@ function main(conf) {
var chunk; var chunk;
switch (type) { switch (type) {
case 'buf': case 'buf':
chunk = new Buffer(size); chunk = Buffer.alloc(size, 'b');
chunk.fill('b');
break; break;
case 'asc': case 'asc':
chunk = new Array(size + 1).join('a'); chunk = new Array(size + 1).join('a');
@ -74,4 +73,3 @@ function main(conf) {
server.close(); server.close();
} }
} }

533
doc/api/buffer.markdown

@ -21,18 +21,112 @@ The `Buffer` class is a global within Node.js, making it unlikely that one
would need to ever use `require('buffer')`. would need to ever use `require('buffer')`.
```js ```js
const buf1 = new Buffer(10); const buf1 = Buffer.alloc(10);
// creates a buffer of length 10 // Creates a zero-filled Buffer of length 10.
const buf2 = new Buffer([1,2,3]); const buf2 = Buffer.alloc(10, 1);
// creates a buffer containing [01, 02, 03] // Creates a Buffer of length 10, filled with 0x01.
const buf3 = new Buffer('test'); const buf3 = Buffer.allocUnsafe(10);
// creates a buffer containing ASCII bytes [74, 65, 73, 74] // Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using either fill() or write().
const buf4 = Buffer.from([1,2,3]);
// Creates a Buffer containing [01, 02, 03].
const buf5 = Buffer.from('test');
// Creates a Buffer containing ASCII bytes [74, 65, 73, 74].
const buf6 = Buffer.from('tést', 'utf8');
// Creates a Buffer containing UTF8 bytes [74, c3, a9, 73, 74].
```
## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
In versions of Node.js prior to v6, `Buffer` instances were created using the
`Buffer` constructor function, which allocates the returned `Buffer`
differently based on what arguments are provided:
* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`),
allocates a new `Buffer` object of the specified size. The memory allocated
for such `Buffer` instances is *not* initialized and *can contain sensitive
data*. Such `Buffer` objects *must* be initialized *manually* by using either
[`buf.fill(0)`][] or by writing to the `Buffer` completely. While this
behavior is *intentional* to improve performance, development experience has
demonstrated that a more explicit distinction is required between creating a
fast-but-uninitialized `Buffer` versus creating a slower-but-safer `Buffer`.
* Passing a string, array, or `Buffer` as the first argument copies the
passed object's data into the `Buffer`.
* Passing an `ArrayBuffer` returns a `Buffer` that shares allocated memory with
the given `ArrayBuffer`.
Because the behavior of `new Buffer()` changes significantly based on the type
of value passed as the first argument, applications that do not properly
validate the input arguments passed to `new Buffer()`, or that fail to
appropriately initialize newly allocated `Buffer` content, can inadvertently
introduce security and reliability issues into their code.
To make the creation of `Buffer` objects more reliable and less error prone,
the various forms of the `new Buffer()` constructor have been **deprecated**
and replaced by separate `Buffer.from()`, `Buffer.alloc()`, and
`Buffer.allocUnsafe()` methods.
*Developers should migrate all existing uses of the `new Buffer()` constructors
to one of these new APIs.*
* [`Buffer.from(array)`][buffer_from_array] returns a new `Buffer` containing
a *copy* of the provided octets.
* [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf]
returns a new `Buffer` that *shares* the same allocated memory as the given
`ArrayBuffer`.
* [`Buffer.from(buffer)`][buffer_from_buffer] returns a new `Buffer`
containing a *copy* of the contents of the given `Buffer`.
* [`Buffer.from(str[, encoding])`][buffer_from_string] returns a new `Buffer`
containing a *copy* of the provided string.
* [`Buffer.alloc(size[, fill[, encoding]])`][buffer_alloc] returns a "filled"
`Buffer` instance of the specified size. This method can be significantly
slower than [`Buffer.allocUnsafe(size)`][buffer_allocunsafe] but ensures that
newly created `Buffer` instances never contain old and potentially sensitive
data.
* [`Buffer.allocUnsafe(size)`][buffer_allocunsafe] returns a new `Buffer` of
the specified `size` whose content *must* be initialized using either
[`buf.fill(0)`][] or written to completely.
`Buffer` instances returned by `Buffer.allocUnsafe(size)` *may* be allocated
off a shared internal memory pool if the `size` is less than or equal to half
`Buffer.poolSize`.
### The `--zero-fill-buffers` command line option
Node.js can be started using the `--zero-fill-buffers` command line option to
force all newly allocated `Buffer` and `SlowBuffer` instances created using
either `new Buffer(size)`, `Buffer.allocUnsafe(size)`, or
`new SlowBuffer(size)` to be *automatically zero-filled* upon creation. Use of
this flag *changes the default behavior* of these methods and *can have a
significant impact* on performance. Use of the `--zero-fill-buffers` option is
recommended only when absolutely necessary to enforce that newly allocated
`Buffer` instances cannot contain potentially sensitive data.
const buf4 = new Buffer('tést', 'utf8');
// creates a buffer containing UTF8 bytes [74, c3, a9, 73, 74]
``` ```
$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
<Buffer 00 00 00 00 00>
```
### What makes `Buffer.allocUnsafe(size)` "unsafe"?
When calling `Buffer.allocUnsafe()`, the segment of allocated memory is
*uninitialized* (it is not zeroed-out). While this design makes the allocation
of memory quite fast, the allocated segment of memory might contain old data
that is potentially sensitive. Using a `Buffer` created by
`Buffer.allocUnsafe(size)` without *completely* overwriting the memory can
allow this old data to be leaked when the `Buffer` memory is read.
While there are clear performance advantages to using `Buffer.allocUnsafe()`,
extra care *must* be taken in order to avoid introducing security
vulnerabilities into an application.
## Buffers and Character Encodings ## Buffers and Character Encodings
@ -42,7 +136,7 @@ convert back and forth between Buffers and ordinary JavaScript string objects
by using an explicit encoding method. by using an explicit encoding method.
```js ```js
const buf = new Buffer('hello world', 'ascii'); const buf = Buffer.from('hello world', 'ascii');
console.log(buf.toString('hex')); console.log(buf.toString('hex'));
// prints: 68656c6c6f20776f726c64 // prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64')); console.log(buf.toString('base64'));
@ -83,24 +177,24 @@ existing Buffer without copying, making `Buffer#slice()` far more efficient.
It is also possible to create new TypedArray instances from a `Buffer` with the It is also possible to create new TypedArray instances from a `Buffer` with the
following caveats: following caveats:
1. The Buffer instances's memory is copied to the TypedArray, not shared. 1. The `Buffer` object's memory is copied to the TypedArray, not shared.
2. The Buffer's memory is interpreted as an array of distinct elements, and not 2. The `Buffer` object's memory is interpreted as an array of distinct
as a byte array of the target type. That is, elements, and not as a byte array of the target type. That is,
`new Uint32Array(new Buffer([1,2,3,4]))` creates a 4-element `Uint32Array` `new Uint32Array(Buffer.from([1,2,3,4]))` creates a 4-element `Uint32Array`
with elements `[1,2,3,4]`, not a `Uint32Array` with a single element with elements `[1,2,3,4]`, not a `Uint32Array` with a single element
`[0x1020304]` or `[0x4030201]`. `[0x1020304]` or `[0x4030201]`.
It is possible to create a new Buffer that shares the same allocated memory as It is possible to create a new `Buffer` that shares the same allocated memory as
a TypedArray instance by using the TypeArray objects `.buffer` property: a TypedArray instance by using the TypeArray object's `.buffer` property:
```js ```js
const arr = new Uint16Array(2); const arr = new Uint16Array(2);
arr[0] = 5000; arr[0] = 5000;
arr[1] = 4000; arr[1] = 4000;
const buf1 = new Buffer(arr); // copies the buffer const buf1 = Buffer.from(arr); // copies the buffer
const buf2 = new Buffer(arr.buffer); // shares the memory with arr; const buf2 = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf1); console.log(buf1);
// Prints: <Buffer 88 a0>, copied buffer has only two elements // Prints: <Buffer 88 a0>, copied buffer has only two elements
@ -114,24 +208,38 @@ console.log(buf2);
// Prints: <Buffer 88 13 70 17> // Prints: <Buffer 88 13 70 17>
``` ```
Note that when creating a Buffer using the TypeArray's `.buffer`, it is not Note that when creating a `Buffer` using the TypedArray's `.buffer`, it is
currently possible to use only a portion of the underlying `ArrayBuffer`. To possible to use only a portion of the underlying `ArrayBuffer` by passing in
create a Buffer that uses only a part of the `ArrayBuffer`, use the `byteOffset` and `length` parameters:
[`buf.slice()`][] function after the Buffer is created:
```js ```js
const arr = new Uint16Array(20); const arr = new Uint16Array(20);
const buf = new Buffer(arr.buffer).slice(0, 16); const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length); console.log(buf.length);
// Prints: 16 // Prints: 16
``` ```
The `Buffer.from()` and [`TypedArray.from()`][] (e.g.`Uint8Array.from()`) have
different signatures and implementations. Specifically, the TypedArray variants
accept a second argument that is a mapping function that is invoked on every
element of the typed array:
* `TypedArray.from(source[, mapFn[, thisArg]])`
The `Buffer.from()` method, however, does not support the use of a mapping
function:
* [`Buffer.from(array)`][buffer_from_array]
* [`Buffer.from(buffer)`][buffer_from_buffer]
* [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf]
* [`Buffer.from(str[, encoding])`][buffer_from_string]
## Buffers and ES6 iteration ## Buffers and ES6 iteration
Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax: Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax:
```js ```js
const buf = new Buffer([1, 2, 3]); const buf = Buffer.from([1, 2, 3]);
for (var b of buf) for (var b of buf)
console.log(b) console.log(b)
@ -152,6 +260,9 @@ It can be constructed in a variety of ways.
### new Buffer(array) ### new Buffer(array)
Stability: 0 - Deprecated: Use [`Buffer.from(array)`][buffer_from_array]
instead.
* `array` {Array} * `array` {Array}
Allocates a new Buffer using an `array` of octets. Allocates a new Buffer using an `array` of octets.
@ -164,6 +275,9 @@ const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);
### new Buffer(buffer) ### new Buffer(buffer)
Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][buffer_from_buffer]
instead.
* `buffer` {Buffer} * `buffer` {Buffer}
Copies the passed `buffer` data onto a new `Buffer` instance. Copies the passed `buffer` data onto a new `Buffer` instance.
@ -179,15 +293,24 @@ console.log(buf2.toString());
// 'buffer' (copy is not changed) // 'buffer' (copy is not changed)
``` ```
### new Buffer(arrayBuffer) ### new Buffer(arrayBuffer[, byteOffset [, length]])
* `arrayBuffer` - The `.buffer` property of a `TypedArray` or a `new Stability: 0 - Deprecated: Use
ArrayBuffer()` [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf]
instead.
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a
`new ArrayBuffer()`
* `byteOffset` {Number} Default: `0`
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
When passed a reference to the `.buffer` property of a `TypedArray` instance, When passed a reference to the `.buffer` property of a `TypedArray` instance,
the newly created Buffer will share the same allocated memory as the the newly created Buffer will share the same allocated memory as the
TypedArray. TypedArray.
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
```js ```js
const arr = new Uint16Array(2); const arr = new Uint16Array(2);
arr[0] = 5000; arr[0] = 5000;
@ -207,18 +330,22 @@ console.log(buf);
### new Buffer(size) ### new Buffer(size)
Stability: 0 - Deprecated: Use
[`Buffer.alloc(size[, fill[, encoding]])`][buffer_alloc] instead (also
see [`Buffer.allocUnsafe(size)`][buffer_allocunsafe]).
* `size` {Number} * `size` {Number}
Allocates a new Buffer of `size` bytes. The `size` must be less than Allocates a new `Buffer` of `size` bytes. The `size` must be less than
or equal to the value of `require('buffer').kMaxLength` (on 64-bit or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
thrown. If a `size` less than 0 is specified, a zero-length Buffer will be thrown. If a `size` less than 0 is specified, a zero-length Buffer will be
created. created.
Unlike `ArrayBuffers`, the underlying memory for Buffer instances created in Unlike `ArrayBuffers`, the underlying memory for `Buffer` instances created in
this way is not initialized. The contents of a newly created `Buffer` are this way is *not initialized*. The contents of a newly created `Buffer` are
unknown and could contain sensitive data. Use [`buf.fill(0)`][] to initialize a unknown and *could contain sensitive data*. Use [`buf.fill(0)`][] to initialize
Buffer to zeroes. a `Buffer` to zeroes.
```js ```js
const buf = new Buffer(5); const buf = new Buffer(5);
@ -232,7 +359,10 @@ console.log(buf);
### new Buffer(str[, encoding]) ### new Buffer(str[, encoding])
* `str` {String} String to encode. Stability: 0 - Deprecated:
Use [`Buffer.from(str[, encoding])`][buffer_from_string] instead.
* `str` {String} string to encode.
* `encoding` {String} Default: `'utf8'` * `encoding` {String} Default: `'utf8'`
Creates a new Buffer containing the given JavaScript string `str`. If Creates a new Buffer containing the given JavaScript string `str`. If
@ -250,6 +380,92 @@ console.log(buf2.toString());
// prints: this is a tést // prints: this is a tést
``` ```
### Class Method: Buffer.alloc(size[, fill[, encoding]])
* `size` {Number}
* `fill` {Value} Default: `undefined`
* `encoding` {String} Default: `utf8`
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be *zero-filled*.
```js
const buf = Buffer.alloc(5);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
The `size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. If a `size` less than 0
is specified, a zero-length `Buffer` will be created.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
`buf.fill(fill)`. See [`buf.fill()`][] for more information.
```js
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// <Buffer 61 61 61 61 61>
```
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling `buf.fill(fill, encoding)`. For example:
```js
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```
Calling `Buffer.alloc(size)` can be significantly slower than the alternative
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
contents will *never contain sensitive data*.
A `TypeError` will be thrown if `size` is not a number.
### Class Method: Buffer.allocUnsafe(size)
* `size` {Number}
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
thrown. If a `size` less than 0 is specified, a zero-length `Buffer` will be
created.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
`Buffer` instances to zeroes.
```js
const buf = Buffer.allocUnsafe(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
A `TypeError` will be thrown if `size` is not a number.
Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
size `Buffer.poolSize` that is used as a pool for the fast allocation of new
`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
`new Buffer(size)` constructor) only when `size` is less than or equal to
`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
value of `Buffer.poolSize` is `8192` but can be modified.
Use of this pre-allocated internal memory pool is a key difference between
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
difference is subtle but can be important when an application requires the
additional performance that `Buffer.allocUnsafe(size)` provides.
### Class Method: Buffer.byteLength(string[, encoding]) ### Class Method: Buffer.byteLength(string[, encoding])
* `string` {String} * `string` {String}
@ -281,14 +497,15 @@ Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
Buffers. This is equivalent is calling [`buf1.compare(buf2)`][]. Buffers. This is equivalent is calling [`buf1.compare(buf2)`][].
```js ```js
const arr = [Buffer('1234'), Buffer('0123')]; const arr = [Buffer.from('1234'), Buffer.from('0123')];
arr.sort(Buffer.compare); arr.sort(Buffer.compare);
``` ```
### Class Method: Buffer.concat(list[, totalLength]) ### Class Method: Buffer.concat(list[, totalLength])
* `list` {Array} List of Buffer objects to concat * `list` {Array} List of Buffer objects to concat
* `totalLength` {Number} Total length of the Buffers in the list when concatenated * `totalLength` {Number} Total length of the Buffers in the list
when concatenated
* Return: {Buffer} * Return: {Buffer}
Returns a new Buffer which is the result of concatenating all the Buffers in Returns a new Buffer which is the result of concatenating all the Buffers in
@ -304,9 +521,9 @@ to provide the length explicitly.
Example: build a single Buffer from a list of three Buffers: Example: build a single Buffer from a list of three Buffers:
```js ```js
const buf1 = new Buffer(10).fill(0); const buf1 = Buffer.alloc(10);
const buf2 = new Buffer(14).fill(0); const buf2 = Buffer.alloc(14);
const buf3 = new Buffer(18).fill(0); const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length; const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength); console.log(totalLength);
@ -319,6 +536,102 @@ console.log(bufA.length);
// 42 // 42
``` ```
### Class Method: Buffer.from(array)
* `array` {Array}
Allocates a new `Buffer` using an `array` of octets.
```js
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
```
A `TypeError` will be thrown if `array` is not an `Array`.
### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
a `new ArrayBuffer()`
* `byteOffset` {Number} Default: `0`
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
When passed a reference to the `.buffer` property of a `TypedArray` instance,
the newly created `Buffer` will share the same allocated memory as the
TypedArray.
```js
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypedArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
```
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
```js
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
```
A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
### Class Method: Buffer.from(buffer)
* `buffer` {Buffer}
Copies the passed `buffer` data onto a new `Buffer` instance.
```js
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
```
A `TypeError` will be thrown if `buffer` is not a `Buffer`.
### Class Method: Buffer.from(str[, encoding])
* `str` {String} String to encode.
* `encoding` {String} Encoding to use, Default: `'utf8'`
Creates a new `Buffer` containing the given JavaScript string `str`. If
provided, the `encoding` parameter identifies the character encoding.
If not provided, `encoding` defaults to `'utf8'`.
```js
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
```
A `TypeError` will be thrown if `str` is not a string.
### Class Method: Buffer.isBuffer(obj) ### Class Method: Buffer.isBuffer(obj)
* `obj` {Object} * `obj` {Object}
@ -347,9 +660,9 @@ Example: copy an ASCII string into a Buffer, one byte at a time:
```js ```js
const str = "Node.js"; const str = "Node.js";
const buf = new Buffer(str.length); const buf = Buffer.allocUnsafe(str.length);
for (var i = 0; i < str.length ; i++) { for (let i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i); buf[i] = str.charCodeAt(i);
} }
@ -371,9 +684,9 @@ Comparison is based on the actual sequence of bytes in each Buffer.
* `-1` is returned if `otherBuffer` should come *after* `buf` when sorted. * `-1` is returned if `otherBuffer` should come *after* `buf` when sorted.
```js ```js
const buf1 = new Buffer('ABC'); const buf1 = Buffer.from('ABC');
const buf2 = new Buffer('BCD'); const buf2 = Buffer.from('BCD');
const buf3 = new Buffer('ABCD'); const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1)); console.log(buf1.compare(buf1));
// Prints: 0 // Prints: 0
@ -405,10 +718,10 @@ Example: build two Buffers, then copy `buf1` from byte 16 through byte 19
into `buf2`, starting at the 8th byte in `buf2`. into `buf2`, starting at the 8th byte in `buf2`.
```js ```js
const buf1 = new Buffer(26); const buf1 = Buffer.allocUnsafe(26);
const buf2 = new Buffer(26).fill('!'); const buf2 = Buffer.allocUnsafe(26).fill('!');
for (var i = 0 ; i < 26 ; i++) { for (let i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a buf1[i] = i + 97; // 97 is ASCII a
} }
@ -421,7 +734,7 @@ Example: Build a single Buffer, then copy data from one region to an overlapping
region in the same Buffer region in the same Buffer
```js ```js
const buf = new Buffer(26); const buf = Buffer.allocUnsafe(26);
for (var i = 0 ; i < 26 ; i++) { for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97; // 97 is ASCII a buf[i] = i + 97; // 97 is ASCII a
@ -441,7 +754,7 @@ Creates and returns an [iterator][] of `[index, byte]` pairs from the Buffer
contents. contents.
```js ```js
const buf = new Buffer('buffer'); const buf = Buffer.from('buffer');
for (var pair of buf.entries()) { for (var pair of buf.entries()) {
console.log(pair); console.log(pair);
} }
@ -463,9 +776,9 @@ Returns a boolean indicating whether `this` and `otherBuffer` have exactly the
same bytes. same bytes.
```js ```js
const buf1 = new Buffer('ABC'); const buf1 = Buffer.from('ABC');
const buf2 = new Buffer('414243', 'hex'); const buf2 = Buffer.from('414243', 'hex');
const buf3 = new Buffer('ABCD'); const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2)); console.log(buf1.equals(buf2));
// Prints: true // Prints: true
@ -488,7 +801,7 @@ This is meant as a small simplification to creating a Buffer. Allowing the
creation and fill of the Buffer to be done on a single line: creation and fill of the Buffer to be done on a single line:
```js ```js
const b = new Buffer(50).fill('h'); const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString()); console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
``` ```
@ -519,22 +832,22 @@ default interpreted as UTF8. Buffers will use the entire Buffer (to compare a
partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255.
```js ```js
const buf = new Buffer('this is a buffer'); const buf = Buffer.from('this is a buffer');
buf.indexOf('this'); buf.indexOf('this');
// returns 0 // returns 0
buf.indexOf('is'); buf.indexOf('is');
// returns 2 // returns 2
buf.indexOf(new Buffer('a buffer')); buf.indexOf(Buffer.from('a buffer'));
// returns 8 // returns 8
buf.indexOf(97); // ascii for 'a' buf.indexOf(97); // ascii for 'a'
// returns 8 // returns 8
buf.indexOf(new Buffer('a buffer example')); buf.indexOf(Buffer.from('a buffer example'));
// returns -1 // returns -1
buf.indexOf(new Buffer('a buffer example').slice(0,8)); buf.indexOf(Buffer.from('a buffer example').slice(0,8));
// returns 8 // returns 8
const utf16Buffer = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
utf16Buffer.indexOf('\u03a3', 0, 'ucs2'); utf16Buffer.indexOf('\u03a3', 0, 'ucs2');
// returns 4 // returns 4
@ -557,19 +870,19 @@ Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255.
The `byteOffset` indicates the index in `buf` where searching begins. The `byteOffset` indicates the index in `buf` where searching begins.
```js ```js
const buf = new Buffer('this is a buffer'); const buf = Buffer.from('this is a buffer');
buf.includes('this'); buf.includes('this');
// returns true // returns true
buf.includes('is'); buf.includes('is');
// returns true // returns true
buf.includes(new Buffer('a buffer')); buf.includes(Buffer.from('a buffer'));
// returns true // returns true
buf.includes(97); // ascii for 'a' buf.includes(97); // ascii for 'a'
// returns true // returns true
buf.includes(new Buffer('a buffer example')); buf.includes(Buffer.from('a buffer example'));
// returns false // returns false
buf.includes(new Buffer('a buffer example').slice(0,8)); buf.includes(Buffer.from('a buffer example').slice(0,8));
// returns true // returns true
buf.includes('this', 4); buf.includes('this', 4);
// returns false // returns false
@ -582,7 +895,7 @@ buf.includes('this', 4);
Creates and returns an [iterator][] of Buffer keys (indices). Creates and returns an [iterator][] of Buffer keys (indices).
```js ```js
const buf = new Buffer('buffer'); const buf = Buffer.from('buffer');
for (var key of buf.keys()) { for (var key of buf.keys()) {
console.log(key); console.log(key);
} }
@ -605,7 +918,7 @@ Buffer. For instance, in the example below, a Buffer with 1234 bytes is
allocated, but only 11 ASCII bytes are written. allocated, but only 11 ASCII bytes are written.
```js ```js
const buf = new Buffer(1234); const buf = Buffer.alloc(1234);
console.log(buf.length); console.log(buf.length);
// Prints: 1234 // Prints: 1234
@ -621,7 +934,7 @@ modify the length of a Buffer should therefore treat `length` as read-only and
use [`buf.slice()`][] to create a new Buffer. use [`buf.slice()`][] to create a new Buffer.
```js ```js
var buf = new Buffer(10); var buf = Buffer.allocUnsafe(10);
buf.write('abcdefghj', 0, 'ascii'); buf.write('abcdefghj', 0, 'ascii');
console.log(buf.length); console.log(buf.length);
// Prints: 10 // Prints: 10
@ -645,7 +958,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
`offset` to be beyond the end of the Buffer. `offset` to be beyond the end of the Buffer.
```js ```js
const buf = new Buffer([1,2,3,4,5,6,7,8]); const buf = Buffer.from([1,2,3,4,5,6,7,8]);
buf.readDoubleBE(); buf.readDoubleBE();
// Returns: 8.20788039913184e-304 // Returns: 8.20788039913184e-304
@ -673,7 +986,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
`offset` to be beyond the end of the Buffer. `offset` to be beyond the end of the Buffer.
```js ```js
const buf = new Buffer([1,2,3,4]); const buf = Buffer.from([1,2,3,4]);
buf.readFloatBE(); buf.readFloatBE();
// Returns: 2.387939260590663e-38 // Returns: 2.387939260590663e-38
@ -700,7 +1013,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
Integers read from the Buffer are interpreted as two's complement signed values. Integers read from the Buffer are interpreted as two's complement signed values.
```js ```js
const buf = new Buffer([1,-2,3,4]); const buf = Buffer.from([1,-2,3,4]);
buf.readInt8(0); buf.readInt8(0);
// returns 1 // returns 1
@ -725,7 +1038,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
Integers read from the Buffer are interpreted as two's complement signed values. Integers read from the Buffer are interpreted as two's complement signed values.
```js ```js
const buf = new Buffer([1,-2,3,4]); const buf = Buffer.from([1,-2,3,4]);
buf.readInt16BE(); buf.readInt16BE();
// returns 510 // returns 510
@ -750,7 +1063,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
Integers read from the Buffer are interpreted as two's complement signed values. Integers read from the Buffer are interpreted as two's complement signed values.
```js ```js
const buf = new Buffer([1,-2,3,4]); const buf = Buffer.from([1,-2,3,4]);
buf.readInt32BE(); buf.readInt32BE();
// returns 33424132 // returns 33424132
@ -771,7 +1084,7 @@ and interprets the result as a two's complement signed value. Supports up to 48
bits of accuracy. For example: bits of accuracy. For example:
```js ```js
const buf = new Buffer(6); const buf = Buffer.allocUnsafe(6);
buf.writeUInt16LE(0x90ab, 0); buf.writeUInt16LE(0x90ab, 0);
buf.writeUInt32LE(0x12345678, 2); buf.writeUInt32LE(0x12345678, 2);
buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
@ -796,7 +1109,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
`offset` to be beyond the end of the Buffer. `offset` to be beyond the end of the Buffer.
```js ```js
const buf = new Buffer([1,-2,3,4]); const buf = Buffer.from([1,-2,3,4]);
buf.readUInt8(0); buf.readUInt8(0);
// returns 1 // returns 1
@ -821,7 +1134,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
Example: Example:
```js ```js
const buf = new Buffer([0x3, 0x4, 0x23, 0x42]); const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);
buf.readUInt16BE(0); buf.readUInt16BE(0);
// Returns: 0x0304 // Returns: 0x0304
@ -854,7 +1167,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the
Example: Example:
```js ```js
const buf = new Buffer([0x3, 0x4, 0x23, 0x42]); const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);
buf.readUInt32BE(0); buf.readUInt32BE(0);
// Returns: 0x03042342 // Returns: 0x03042342
@ -875,7 +1188,7 @@ and interprets the result as an unsigned integer. Supports up to 48
bits of accuracy. For example: bits of accuracy. For example:
```js ```js
const buf = new Buffer(6); const buf = Buffer.allocUnsafe(6);
buf.writeUInt16LE(0x90ab, 0); buf.writeUInt16LE(0x90ab, 0);
buf.writeUInt32LE(0x12345678, 2); buf.writeUInt32LE(0x12345678, 2);
buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
@ -904,7 +1217,7 @@ Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
byte from the original Buffer. byte from the original Buffer.
```js ```js
const buf1 = new Buffer(26); const buf1 = Buffer.allocUnsafe(26);
for (var i = 0 ; i < 26 ; i++) { for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a buf1[i] = i + 97; // 97 is ASCII a
@ -922,7 +1235,7 @@ Specifying negative indexes causes the slice to be generated relative to the
end of the Buffer rather than the beginning. end of the Buffer rather than the beginning.
```js ```js
const buf = new Buffer('buffer'); const buf = Buffer.from('buffer');
buf.slice(-6, -1).toString(); buf.slice(-6, -1).toString();
// Returns 'buffe', equivalent to buf.slice(0, 5) // Returns 'buffe', equivalent to buf.slice(0, 5)
@ -943,7 +1256,7 @@ Decodes and returns a string from the Buffer data using the specified
character set `encoding`. character set `encoding`.
```js ```js
const buf = new Buffer(26); const buf = Buffer.allocUnsafe(26);
for (var i = 0 ; i < 26 ; i++) { for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97; // 97 is ASCII a buf[i] = i + 97; // 97 is ASCII a
} }
@ -967,7 +1280,7 @@ implicitly calls this function when stringifying a Buffer instance.
Example: Example:
```js ```js
const buf = new Buffer('test'); const buf = Buffer.from('test');
const json = JSON.stringify(buf); const json = JSON.stringify(buf);
console.log(json); console.log(json);
@ -975,7 +1288,7 @@ console.log(json);
const copy = JSON.parse(json, (key, value) => { const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' return value && value.type === 'Buffer'
? new Buffer(value.data) ? Buffer.from(value.data)
: value; : value;
}); });
@ -991,7 +1304,7 @@ Creates and returns an [iterator][] for Buffer values (bytes). This function is
called automatically when the Buffer is used in a `for..of` statement. called automatically when the Buffer is used in a `for..of` statement.
```js ```js
const buf = new Buffer('buffer'); const buf = Buffer.from('buffer');
for (var value of buf.values()) { for (var value of buf.values()) {
console.log(value); console.log(value);
} }
@ -1030,7 +1343,7 @@ string will be written however, it will not write only partially encoded
characters. characters.
```js ```js
const buf = new Buffer(256); const buf = Buffer.allocUnsafe(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0); const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾ // Prints: 12 bytes: ½ + ¼ = ¾
@ -1056,7 +1369,7 @@ should not be used unless you are certain of correctness.
Example: Example:
```js ```js
const buf = new Buffer(8); const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(0xdeadbeefcafebabe, 0); buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
console.log(buf); console.log(buf);
@ -1089,7 +1402,7 @@ should not be used unless you are certain of correctness.
Example: Example:
```js ```js
const buf = new Buffer(4); const buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(0xcafebabe, 0); buf.writeFloatBE(0xcafebabe, 0);
console.log(buf); console.log(buf);
@ -1119,7 +1432,7 @@ should not be used unless you are certain of correctness.
The `value` is interpreted and written as a two's complement signed integer. The `value` is interpreted and written as a two's complement signed integer.
```js ```js
const buf = new Buffer(2); const buf = Buffer.allocUnsafe(2);
buf.writeInt8(2, 0); buf.writeInt8(2, 0);
buf.writeInt8(-2, 1); buf.writeInt8(-2, 1);
console.log(buf); console.log(buf);
@ -1146,7 +1459,7 @@ should not be used unless you are certain of correctness.
The `value` is interpreted and written as a two's complement signed integer. The `value` is interpreted and written as a two's complement signed integer.
```js ```js
const buf = new Buffer(4); const buf = Buffer.allocUnsafe(4);
buf.writeInt16BE(0x0102,0); buf.writeInt16BE(0x0102,0);
buf.writeInt16LE(0x0304,2); buf.writeInt16LE(0x0304,2);
console.log(buf); console.log(buf);
@ -1173,7 +1486,7 @@ should not be used unless you are certain of correctness.
The `value` is interpreted and written as a two's complement signed integer. The `value` is interpreted and written as a two's complement signed integer.
```js ```js
const buf = new Buffer(8); const buf = Buffer.allocUnsafe(8);
buf.writeInt32BE(0x01020304,0); buf.writeInt32BE(0x01020304,0);
buf.writeInt32LE(0x05060708,4); buf.writeInt32LE(0x05060708,4);
console.log(buf); console.log(buf);
@ -1193,12 +1506,12 @@ Writes `value` to the Buffer at the specified `offset` and `byteLength`.
Supports up to 48 bits of accuracy. For example: Supports up to 48 bits of accuracy. For example:
```js ```js
const buf1 = new Buffer(6); const buf1 = Buffer.allocUnsafe(6);
buf1.writeUIntBE(0x1234567890ab, 0, 6); buf1.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf1); console.log(buf1);
// Prints: <Buffer 12 34 56 78 90 ab> // Prints: <Buffer 12 34 56 78 90 ab>
const buf2 = new Buffer(6); const buf2 = Buffer.allocUnsafe(6);
buf2.writeUIntLE(0x1234567890ab, 0, 6); buf2.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf2); console.log(buf2);
// Prints: <Buffer ab 90 78 56 34 12> // Prints: <Buffer ab 90 78 56 34 12>
@ -1227,7 +1540,7 @@ should not be used unless you are certain of correctness.
Example: Example:
```js ```js
const buf = new Buffer(4); const buf = Buffer.allocUnsafe(4);
buf.writeUInt8(0x3, 0); buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1); buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2); buf.writeUInt8(0x23, 2);
@ -1257,7 +1570,7 @@ should not be used unless you are certain of correctness.
Example: Example:
```js ```js
const buf = new Buffer(4); const buf = Buffer.allocUnsafe(4);
buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2); buf.writeUInt16BE(0xbeef, 2);
@ -1291,7 +1604,7 @@ should not be used unless you are certain of correctness.
Example: Example:
```js ```js
const buf = new Buffer(4); const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(0xfeedface, 0); buf.writeUInt32BE(0xfeedface, 0);
console.log(buf); console.log(buf);
@ -1316,7 +1629,7 @@ Writes `value` to the Buffer at the specified `offset` and `byteLength`.
Supports up to 48 bits of accuracy. For example: Supports up to 48 bits of accuracy. For example:
```js ```js
const buf = new Buffer(6); const buf = Buffer.allocUnsafe(6);
buf.writeUIntBE(0x1234567890ab, 0, 6); buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf); console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab> // Prints: <Buffer 12 34 56 78 90 ab>
@ -1358,7 +1671,7 @@ const store = [];
socket.on('readable', () => { socket.on('readable', () => {
var data = socket.read(); var data = socket.read();
// allocate for retained data // allocate for retained data
var sb = new SlowBuffer(10); var sb = SlowBuffer(10);
// copy the data into the new allocation // copy the data into the new allocation
data.copy(sb, 0, 0, 10); data.copy(sb, 0, 0, 10);
store.push(sb); store.push(sb);
@ -1368,8 +1681,34 @@ socket.on('readable', () => {
Use of `SlowBuffer` should be used only as a last resort *after* a developer Use of `SlowBuffer` should be used only as a last resort *after* a developer
has observed undue memory retention in their applications. has observed undue memory retention in their applications.
[`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes ### new SlowBuffer(size)
* `size` Number
Allocates a new `SlowBuffer` of `size` bytes. The `size` must be less than
or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
thrown. If a `size` less than 0 is specified, a zero-length `SlowBuffer` will be
created.
The underlying memory for `SlowBuffer` instances is *not initialized*. The
contents of a newly created `SlowBuffer` are unknown and could contain
sensitive data. Use [`buf.fill(0)`][] to initialize a `SlowBuffer` to zeroes.
```js
const SlowBuffer = require('buffer').SlowBuffer;
const buf = new SlowBuffer(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
[`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf [`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
[`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
[`buf.entries()`]: #buffer_buf_entries [`buf.entries()`]: #buffer_buf_entries
[`buf.fill(0)`]: #buffer_buf_fill_value_offset_end [`buf.fill(0)`]: #buffer_buf_fill_value_offset_end
[`buf.keys()`]: #buffer_buf_keys [`buf.keys()`]: #buffer_buf_keys
@ -1380,5 +1719,11 @@ has observed undue memory retention in their applications.
[`RangeError`]: errors.html#errors_class_rangeerror [`RangeError`]: errors.html#errors_class_rangeerror
[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length [`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
[`util.inspect()`]: util.html#util_util_inspect_object_options [`util.inspect()`]: util.html#util_util_inspect_object_options
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
[RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5 [RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5
[buffer_from_array]: #buffer_class_method_buffer_from_array
[buffer_from_buffer]: #buffer_class_method_buffer_from_buffer
[buffer_from_arraybuf]: #buffer_class_method_buffer_from_arraybuffer
[buffer_from_string]: #buffer_class_method_buffer_from_str_encoding
[buffer_allocunsafe]: #buffer_class_method_buffer_allocraw_size
[buffer_alloc]: #buffer_class_method_buffer_alloc_size_fill_encoding
[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from

3
doc/node.1

@ -66,6 +66,9 @@ and servers.
--prof-process process v8 profiler output generated using --prof --prof-process process v8 profiler output generated using --prof
--zero-fill-buffers automatically zero-fill all newly allocated
Buffer and SlowBuffer instances
--v8-options print v8 command line options --v8-options print v8 command line options
--tls-cipher-list=list use an alternative default TLS cipher list --tls-cipher-list=list use an alternative default TLS cipher list

2
lib/_debugger.js

@ -108,7 +108,7 @@ Protocol.prototype.execute = function(d) {
var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); var resRawByteLength = Buffer.byteLength(res.raw, 'utf8');
if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) { if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) {
var buf = new Buffer(resRawByteLength); var buf = Buffer.allocUnsafe(resRawByteLength);
buf.write(res.raw, 0, resRawByteLength, 'utf8'); buf.write(res.raw, 0, resRawByteLength, 'utf8');
res.body = res.body =
buf.slice(this.bodyStartByteIndex, buf.slice(this.bodyStartByteIndex,

2
lib/_http_client.js

@ -97,7 +97,7 @@ function ClientRequest(options, cb) {
if (options.auth && !this.getHeader('Authorization')) { if (options.auth && !this.getHeader('Authorization')) {
//basic auth //basic auth
this.setHeader('Authorization', 'Basic ' + this.setHeader('Authorization', 'Basic ' +
new Buffer(options.auth).toString('base64')); Buffer.from(options.auth).toString('base64'));
} }
if (method === 'GET' || if (method === 'GET' ||

2
lib/_http_outgoing.js

@ -526,7 +526,7 @@ OutgoingMessage.prototype.addTrailers = function(headers) {
}; };
const crlf_buf = new Buffer('\r\n'); const crlf_buf = Buffer.from('\r\n');
OutgoingMessage.prototype.end = function(data, encoding, callback) { OutgoingMessage.prototype.end = function(data, encoding, callback) {

4
lib/_stream_readable.js

@ -103,7 +103,7 @@ Readable.prototype.push = function(chunk, encoding) {
if (!state.objectMode && typeof chunk === 'string') { if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding; encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) { if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding); chunk = Buffer.from(chunk, encoding);
encoding = ''; encoding = '';
} }
} }
@ -866,7 +866,7 @@ function fromList(n, state) {
if (stringMode) if (stringMode)
ret = ''; ret = '';
else else
ret = new Buffer(n); ret = Buffer.allocUnsafe(n);
var c = 0; var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) { for (var i = 0, l = list.length; i < l && c < n; i++) {

2
lib/_stream_writable.js

@ -252,7 +252,7 @@ function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && if (!state.objectMode &&
state.decodeStrings !== false && state.decodeStrings !== false &&
typeof chunk === 'string') { typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding); chunk = Buffer.from(chunk, encoding);
} }
return chunk; return chunk;
} }

2
lib/_tls_legacy.js

@ -23,7 +23,7 @@ function SlabBuffer() {
SlabBuffer.prototype.create = function create() { SlabBuffer.prototype.create = function create() {
this.isFull = false; this.isFull = false;
this.pool = new Buffer(tls.SLAB_BUFFER_SIZE); this.pool = Buffer.allocUnsafe(tls.SLAB_BUFFER_SIZE);
this.offset = 0; this.offset = 0;
this.remaining = this.pool.length; this.remaining = this.pool.length;
}; };

4
lib/_tls_wrap.js

@ -602,7 +602,7 @@ TLSSocket.prototype.setServername = function(name) {
TLSSocket.prototype.setSession = function(session) { TLSSocket.prototype.setSession = function(session) {
if (typeof session === 'string') if (typeof session === 'string')
session = new Buffer(session, 'binary'); session = Buffer.from(session, 'binary');
this._handle.setSession(session); this._handle.setSession(session);
}; };
@ -845,7 +845,7 @@ Server.prototype._getServerData = function() {
Server.prototype._setServerData = function(data) { Server.prototype._setServerData = function(data) {
this.setTicketKeys(new Buffer(data.ticketKeys, 'hex')); this.setTicketKeys(Buffer.from(data.ticketKeys, 'hex'));
}; };

2
lib/assert.js

@ -173,7 +173,7 @@ function _deepEqual(actual, expected, strict) {
// If both values are instances of typed arrays, wrap them in // If both values are instances of typed arrays, wrap them in
// a Buffer each to increase performance // a Buffer each to increase performance
} else if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected)) { } else if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected)) {
return compare(new Buffer(actual), new Buffer(expected)) === 0; return compare(Buffer.from(actual), Buffer.from(expected)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is // 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified // determined by having the same number of owned properties (as verified

138
lib/buffer.js

@ -9,6 +9,8 @@ exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50; exports.INSPECT_MAX_BYTES = 50;
exports.kMaxLength = binding.kMaxLength; exports.kMaxLength = binding.kMaxLength;
const kFromErrorMsg = 'First argument must be a string, Buffer, ' +
'ArrayBuffer, Array, or array-like object.';
Buffer.poolSize = 8 * 1024; Buffer.poolSize = 8 * 1024;
var poolSize, poolOffset, allocPool; var poolSize, poolOffset, allocPool;
@ -42,34 +44,90 @@ function alignPool() {
} }
} }
/**
function Buffer(arg, encoding) { * The Buffer() construtor is "soft deprecated" ... that is, it is deprecated
* in the documentation and should not be used moving forward. Rather,
* developers should use one of the three new factory APIs: Buffer.from(),
* Buffer.allocUnsafe() or Buffer.alloc() based on their specific needs. There
* is no hard deprecation because of the extent to which the Buffer constructor
* is used in the ecosystem currently -- a hard deprecation would introduce too
* much breakage at this time. It's not likely that the Buffer constructors
* would ever actually be removed.
**/
function Buffer(arg, encodingOrOffset, length) {
// Common case. // Common case.
if (typeof arg === 'number') { if (typeof arg === 'number') {
if (typeof encoding === 'string') { if (typeof encodingOrOffset === 'string') {
throw new Error( throw new Error(
'If encoding is specified then the first argument must be a string' 'If encoding is specified then the first argument must be a string'
); );
} }
// If less than zero, or NaN. return Buffer.allocUnsafe(arg);
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, encoding);
} }
return Buffer.from(arg, encodingOrOffset, length);
// Unusual.
return fromObject(arg);
} }
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function(value, encodingOrOffset, length) {
if (typeof value === 'number')
throw new TypeError('"value" argument must not be a number');
if (value instanceof ArrayBuffer)
return fromArrayBuffer(value, encodingOrOffset, length);
if (typeof value === 'string')
return fromString(value, encodingOrOffset);
return fromObject(value);
};
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(Buffer, Uint8Array); Object.setPrototypeOf(Buffer, Uint8Array);
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function(size, fill, encoding) {
if (typeof size !== 'number')
throw new TypeError('"size" argument must be a number');
if (size <= 0)
return createBuffer(size);
if (fill !== undefined) {
// Since we are filling anyway, don't zero fill initially.
flags[kNoZeroFill] = 1;
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string' ?
createBuffer(size).fill(fill, encoding) :
createBuffer(size).fill(fill);
}
flags[kNoZeroFill] = 0;
return createBuffer(size);
};
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer
* instance. If `--zero-fill-buffers` is set, will zero-fill the buffer.
**/
Buffer.allocUnsafe = function(size) {
if (typeof size !== 'number')
throw new TypeError('"size" argument must be a number');
if (size > 0)
flags[kNoZeroFill] = 1;
return allocate(size);
};
// If --zero-fill-buffers command line argument is set, a zero-filled
// buffer is returned.
function SlowBuffer(length) { function SlowBuffer(length) {
if (+length != length) if (+length != length)
length = 0; length = 0;
@ -108,6 +166,9 @@ function fromString(string, encoding) {
if (typeof encoding !== 'string' || encoding === '') if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8'; encoding = 'utf8';
if (!Buffer.isEncoding(encoding))
throw new TypeError('"encoding" must be a valid string encoding');
var length = byteLength(string, encoding); var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1)) if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding); return binding.createFromString(string, encoding);
@ -129,6 +190,16 @@ function fromArrayLike(obj) {
return b; return b;
} }
function fromArrayBuffer(obj, byteOffset, length) {
byteOffset >>>= 0;
if (typeof length === 'undefined')
return binding.createFromArrayBuffer(obj, byteOffset);
length >>>= 0;
return binding.createFromArrayBuffer(obj, byteOffset, length);
}
function fromObject(obj) { function fromObject(obj) {
if (obj instanceof Buffer) { if (obj instanceof Buffer) {
const b = allocate(obj.length); const b = allocate(obj.length);
@ -140,26 +211,20 @@ function fromObject(obj) {
return b; return b;
} }
if (obj == null) { if (obj) {
throw new TypeError('Must start with number, buffer, array or string'); if (obj.buffer instanceof ArrayBuffer || 'length' in obj) {
} if (typeof obj.length !== 'number' || obj.length !== obj.length) {
return allocate(0);
if (obj instanceof ArrayBuffer) { }
return binding.createFromArrayBuffer(obj); return fromArrayLike(obj);
}
if (obj.buffer instanceof ArrayBuffer || 'length' in obj) {
if (typeof obj.length !== 'number' || obj.length !== obj.length) {
return allocate(0);
} }
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) { if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data); return fromArrayLike(obj.data);
}
} }
throw new TypeError('Must start with number, buffer, array or string'); throw new TypeError(kFromErrorMsg);
} }
@ -215,7 +280,7 @@ Buffer.concat = function(list, length) {
throw new TypeError('"list" argument must be an Array of Buffers'); throw new TypeError('"list" argument must be an Array of Buffers');
if (list.length === 0) if (list.length === 0)
return new Buffer(0); return Buffer.alloc(0);
if (length === undefined) { if (length === undefined) {
length = 0; length = 0;
@ -225,7 +290,7 @@ Buffer.concat = function(list, length) {
length = length >>> 0; length = length >>> 0;
} }
var buffer = new Buffer(length); var buffer = Buffer.allocUnsafe(length);
var pos = 0; var pos = 0;
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
var buf = list[i]; var buf = list[i];
@ -454,7 +519,7 @@ function slowIndexOf(buffer, val, byteOffset, encoding) {
case 'ascii': case 'ascii':
case 'hex': case 'hex':
return binding.indexOfBuffer( return binding.indexOfBuffer(
buffer, Buffer(val, encoding), byteOffset, encoding); buffer, Buffer.from(val, encoding), byteOffset, encoding);
default: default:
if (loweredCase) { if (loweredCase) {
@ -518,6 +583,11 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) {
if (code < 256) if (code < 256)
val = code; val = code;
} }
if (val.length === 0) {
// Previously, if val === '', the Buffer would not fill,
// which is rather surprising.
val = 0;
}
if (encoding !== undefined && typeof encoding !== 'string') { if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string'); throw new TypeError('encoding must be a string');
} }

2
lib/child_process.js

@ -422,7 +422,7 @@ function spawnSync(/*file, args, options*/) {
if (Buffer.isBuffer(input)) if (Buffer.isBuffer(input))
pipe.input = input; pipe.input = input;
else if (typeof input === 'string') else if (typeof input === 'string')
pipe.input = new Buffer(input, options.encoding); pipe.input = Buffer.from(input, options.encoding);
else else
throw new TypeError(util.format( throw new TypeError(util.format(
'stdio[%d] should be Buffer or string not %s', 'stdio[%d] should be Buffer or string not %s',

2
lib/crypto.js

@ -33,7 +33,7 @@ function toBuf(str, encoding) {
if (typeof str === 'string') { if (typeof str === 'string') {
if (encoding === 'buffer' || !encoding) if (encoding === 'buffer' || !encoding)
encoding = 'utf8'; encoding = 'utf8';
return new Buffer(str, encoding); return Buffer.from(str, encoding);
} }
return str; return str;
} }

6
lib/dgram.js

@ -252,7 +252,7 @@ Socket.prototype.sendto = function(buffer,
function sliceBuffer(buffer, offset, length) { function sliceBuffer(buffer, offset, length) {
if (typeof buffer === 'string') if (typeof buffer === 'string')
buffer = new Buffer(buffer); buffer = Buffer.from(buffer);
else if (!(buffer instanceof Buffer)) else if (!(buffer instanceof Buffer))
throw new TypeError('First argument must be a buffer or string'); throw new TypeError('First argument must be a buffer or string');
@ -267,7 +267,7 @@ function fixBuffer(buffer) {
for (var i = 0, l = buffer.length; i < l; i++) { for (var i = 0, l = buffer.length; i < l; i++) {
var buf = buffer[i]; var buf = buffer[i];
if (typeof buf === 'string') if (typeof buf === 'string')
buffer[i] = new Buffer(buf); buffer[i] = Buffer.from(buf);
else if (!(buf instanceof Buffer)) else if (!(buf instanceof Buffer))
return false; return false;
} }
@ -318,7 +318,7 @@ Socket.prototype.send = function(buffer,
if (!Array.isArray(buffer)) { if (!Array.isArray(buffer)) {
if (typeof buffer === 'string') { if (typeof buffer === 'string') {
buffer = [ new Buffer(buffer) ]; buffer = [ Buffer.from(buffer) ];
} else if (!(buffer instanceof Buffer)) { } else if (!(buffer instanceof Buffer)) {
throw new TypeError('First argument must be a buffer or a string'); throw new TypeError('First argument must be a buffer or a string');
} else { } else {

22
lib/fs.js

@ -321,7 +321,7 @@ ReadFileContext.prototype.read = function() {
var length; var length;
if (this.size === 0) { if (this.size === 0) {
buffer = this.buffer = new SlowBuffer(kReadFileBufferLength); buffer = this.buffer = SlowBuffer(kReadFileBufferLength);
offset = 0; offset = 0;
length = kReadFileBufferLength; length = kReadFileBufferLength;
} else { } else {
@ -389,7 +389,7 @@ function readFileAfterStat(err, st) {
return context.close(err); return context.close(err);
} }
context.buffer = new SlowBuffer(size); context.buffer = SlowBuffer(size);
context.read(); context.read();
} }
@ -486,7 +486,7 @@ fs.readFileSync = function(path, options) {
} else { } else {
threw = true; threw = true;
try { try {
buffer = new Buffer(size); buffer = Buffer.allocUnsafe(size);
threw = false; threw = false;
} finally { } finally {
if (threw && !isUserFd) fs.closeSync(fd); if (threw && !isUserFd) fs.closeSync(fd);
@ -504,7 +504,7 @@ fs.readFileSync = function(path, options) {
} else { } else {
// the kernel lies about many files. // the kernel lies about many files.
// Go ahead and try to read some bytes. // Go ahead and try to read some bytes.
buffer = new Buffer(8192); buffer = Buffer.allocUnsafe(8192);
bytesRead = fs.readSync(fd, buffer, 0, 8192); bytesRead = fs.readSync(fd, buffer, 0, 8192);
if (bytesRead) { if (bytesRead) {
buffers.push(buffer.slice(0, bytesRead)); buffers.push(buffer.slice(0, bytesRead));
@ -635,7 +635,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) {
position = arguments[2]; position = arguments[2];
length = arguments[1]; length = arguments[1];
buffer = new Buffer(length); buffer = Buffer.allocUnsafe(length);
offset = 0; offset = 0;
callback = function(err, bytesRead) { callback = function(err, bytesRead) {
@ -695,7 +695,7 @@ fs.readSync = function(fd, buffer, offset, length, position) {
position = arguments[2]; position = arguments[2];
length = arguments[1]; length = arguments[1];
buffer = new Buffer(length); buffer = Buffer.allocUnsafe(length);
offset = 0; offset = 0;
} }
@ -1260,8 +1260,8 @@ fs.writeFile = function(path, data, options, callback_) {
}); });
function writeFd(fd, isUserFd) { function writeFd(fd, isUserFd) {
var buffer = (data instanceof Buffer) ? data : new Buffer('' + data, var buffer = (data instanceof Buffer) ?
options.encoding || 'utf8'); data : Buffer.from('' + data, options.encoding || 'utf8');
var position = /a/.test(flag) ? null : 0; var position = /a/.test(flag) ? null : 0;
writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback); writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback);
@ -1284,7 +1284,7 @@ fs.writeFileSync = function(path, data, options) {
var fd = isUserFd ? path : fs.openSync(path, flag, options.mode); var fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
if (!(data instanceof Buffer)) { if (!(data instanceof Buffer)) {
data = new Buffer('' + data, options.encoding || 'utf8'); data = Buffer.from('' + data, options.encoding || 'utf8');
} }
var offset = 0; var offset = 0;
var length = data.length; var length = data.length;
@ -1738,7 +1738,7 @@ fs.realpath = function realpath(p, cache, cb) {
var pool; var pool;
function allocNewPool(poolSize) { function allocNewPool(poolSize) {
pool = new Buffer(poolSize); pool = Buffer.allocUnsafe(poolSize);
pool.used = 0; pool.used = 0;
} }
@ -2108,7 +2108,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) {
// Change strings to buffers. SLOW // Change strings to buffers. SLOW
if (typeof data === 'string') { if (typeof data === 'string') {
data = new Buffer(data, encoding); data = Buffer.from(data, encoding);
} }
fs.writeSync(this.fd, data, 0, data.length); fs.writeSync(this.fd, data, 0, data.length);

2
lib/internal/v8_prof_polyfill.js

@ -60,7 +60,7 @@ try {
process.exit(1); process.exit(1);
} }
const fd = fs.openSync(logFile, 'r'); const fd = fs.openSync(logFile, 'r');
const buf = new Buffer(4096); const buf = Buffer.allocUnsafe(4096);
const dec = new (require('string_decoder').StringDecoder)('utf-8'); const dec = new (require('string_decoder').StringDecoder)('utf-8');
var line = ''; var line = '';
versionCheck(); versionCheck();

2
lib/net.js

@ -724,7 +724,7 @@ function createWriteReq(req, handle, data, encoding) {
return handle.writeUcs2String(req, data); return handle.writeUcs2String(req, data);
default: default:
return handle.writeBuffer(req, new Buffer(data, encoding)); return handle.writeBuffer(req, Buffer.from(data, encoding));
} }
} }

2
lib/querystring.js

@ -8,7 +8,7 @@ const Buffer = require('buffer').Buffer;
// a safe fast alternative to decodeURIComponent // a safe fast alternative to decodeURIComponent
QueryString.unescapeBuffer = function(s, decodeSpaces) { QueryString.unescapeBuffer = function(s, decodeSpaces) {
var out = new Buffer(s.length); var out = Buffer.allocUnsafe(s.length);
var state = 0; var state = 0;
var n, m, hexchar; var n, m, hexchar;

2
lib/string_decoder.js

@ -44,7 +44,7 @@ const StringDecoder = exports.StringDecoder = function(encoding) {
// Enough space to store all bytes of a single character. UTF-8 needs 4 // Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6); this.charBuffer = Buffer.allocUnsafe(6);
// Number of bytes received for the current incomplete multi-byte character. // Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0; this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character. // Number of bytes expected for the current incomplete multi-byte character.

4
lib/tls.js

@ -33,7 +33,7 @@ exports.getCiphers = function() {
// Convert protocols array into valid OpenSSL protocols list // Convert protocols array into valid OpenSSL protocols list
// ("\x06spdy/2\x08http/1.1\x08http/1.0") // ("\x06spdy/2\x08http/1.1\x08http/1.0")
function convertProtocols(protocols) { function convertProtocols(protocols) {
var buff = new Buffer(protocols.reduce(function(p, c) { var buff = Buffer.allocUnsafe(protocols.reduce(function(p, c) {
return p + 1 + Buffer.byteLength(c); return p + 1 + Buffer.byteLength(c);
}, 0)); }, 0));
@ -67,7 +67,7 @@ exports.convertALPNProtocols = function(protocols, out) {
// If it's already a Buffer - store it // If it's already a Buffer - store it
if (protocols instanceof Buffer) { if (protocols instanceof Buffer) {
// copy new buffer not to be modified by user // copy new buffer not to be modified by user
out.ALPNProtocols = new Buffer(protocols); out.ALPNProtocols = Buffer.from(protocols);
} }
}; };

10
lib/zlib.js

@ -230,7 +230,7 @@ function zlibBuffer(engine, buffer, callback) {
function zlibBufferSync(engine, buffer) { function zlibBufferSync(engine, buffer) {
if (typeof buffer === 'string') if (typeof buffer === 'string')
buffer = new Buffer(buffer); buffer = Buffer.from(buffer);
if (!(buffer instanceof Buffer)) if (!(buffer instanceof Buffer))
throw new TypeError('Not a string or buffer'); throw new TypeError('Not a string or buffer');
@ -378,7 +378,7 @@ function Zlib(opts, mode) {
strategy, strategy,
opts.dictionary); opts.dictionary);
this._buffer = new Buffer(this._chunkSize); this._buffer = Buffer.allocUnsafe(this._chunkSize);
this._offset = 0; this._offset = 0;
this._closed = false; this._closed = false;
this._level = level; this._level = level;
@ -426,7 +426,7 @@ Zlib.prototype.reset = function() {
// This is the _flush function called by the transform class, // This is the _flush function called by the transform class,
// internally, when the last chunk has been written. // internally, when the last chunk has been written.
Zlib.prototype._flush = function(callback) { Zlib.prototype._flush = function(callback) {
this._transform(new Buffer(0), '', callback); this._transform(Buffer.alloc(0), '', callback);
}; };
Zlib.prototype.flush = function(kind, callback) { Zlib.prototype.flush = function(kind, callback) {
@ -449,7 +449,7 @@ Zlib.prototype.flush = function(kind, callback) {
} }
} else { } else {
this._flushFlag = kind; this._flushFlag = kind;
this.write(new Buffer(0), '', callback); this.write(Buffer.alloc(0), '', callback);
} }
}; };
@ -580,7 +580,7 @@ Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
if (availOutAfter === 0 || self._offset >= self._chunkSize) { if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize; availOutBefore = self._chunkSize;
self._offset = 0; self._offset = 0;
self._buffer = new Buffer(self._chunkSize); self._buffer = Buffer.allocUnsafe(self._chunkSize);
} }
if (availOutAfter === 0) { if (availOutAfter === 0) {

8
src/node.cc

@ -955,7 +955,9 @@ Local<Value> WinapiErrnoException(Isolate* isolate,
void* ArrayBufferAllocator::Allocate(size_t size) { void* ArrayBufferAllocator::Allocate(size_t size) {
if (env_ == nullptr || !env_->array_buffer_allocator_info()->no_zero_fill()) if (env_ == nullptr ||
!env_->array_buffer_allocator_info()->no_zero_fill() ||
zero_fill_all_buffers)
return calloc(size, 1); return calloc(size, 1);
env_->array_buffer_allocator_info()->reset_fill_flag(); env_->array_buffer_allocator_info()->reset_fill_flag();
return malloc(size); return malloc(size);
@ -3312,6 +3314,8 @@ static void PrintHelp() {
"snapshots\n" "snapshots\n"
" --prof-process process v8 profiler output generated\n" " --prof-process process v8 profiler output generated\n"
" using --prof\n" " using --prof\n"
" --zero-fill-buffers automatically zero-fill all newly allocated\n"
" Buffer and SlowBuffer instances\n"
" --v8-options print v8 command line options\n" " --v8-options print v8 command line options\n"
#if HAVE_OPENSSL #if HAVE_OPENSSL
" --tls-cipher-list=val use an alternative default TLS cipher list\n" " --tls-cipher-list=val use an alternative default TLS cipher list\n"
@ -3455,6 +3459,8 @@ static void ParseArgs(int* argc,
} else if (strcmp(arg, "--prof-process") == 0) { } else if (strcmp(arg, "--prof-process") == 0) {
prof_process = true; prof_process = true;
short_circuit = true; short_circuit = true;
} else if (strcmp(arg, "--zero-fill-buffers") == 0) {
zero_fill_all_buffers = true;
} else if (strcmp(arg, "--v8-options") == 0) { } else if (strcmp(arg, "--v8-options") == 0) {
new_v8_argv[new_v8_argc] = "--help"; new_v8_argv[new_v8_argc] = "--help";
new_v8_argc += 1; new_v8_argc += 1;

27
src/node_buffer.cc

@ -48,7 +48,14 @@
CHECK_NOT_OOB(end <= end_max); \ CHECK_NOT_OOB(end <= end_max); \
size_t length = end - start; size_t length = end - start;
#define BUFFER_MALLOC(length) \
zero_fill_all_buffers ? calloc(length, 1) : malloc(length)
namespace node { namespace node {
// if true, all Buffer and SlowBuffer instances will automatically zero-fill
bool zero_fill_all_buffers = false;
namespace Buffer { namespace Buffer {
using v8::ArrayBuffer; using v8::ArrayBuffer;
@ -74,7 +81,6 @@ using v8::Uint8Array;
using v8::Value; using v8::Value;
using v8::WeakCallbackInfo; using v8::WeakCallbackInfo;
class CallbackInfo { class CallbackInfo {
public: public:
static inline void Free(char* data, void* hint); static inline void Free(char* data, void* hint);
@ -210,7 +216,7 @@ MaybeLocal<Object> New(Isolate* isolate,
// nullptr for zero-sized allocation requests. Normalize by always using // nullptr for zero-sized allocation requests. Normalize by always using
// a nullptr. // a nullptr.
if (length > 0) { if (length > 0) {
data = static_cast<char*>(malloc(length)); data = static_cast<char*>(BUFFER_MALLOC(length));
if (data == nullptr) if (data == nullptr)
return Local<Object>(); return Local<Object>();
@ -256,7 +262,7 @@ MaybeLocal<Object> New(Environment* env, size_t length) {
void* data; void* data;
if (length > 0) { if (length > 0) {
data = malloc(length); data = BUFFER_MALLOC(length);
if (data == nullptr) if (data == nullptr)
return Local<Object>(); return Local<Object>();
} else { } else {
@ -419,7 +425,20 @@ void CreateFromArrayBuffer(const FunctionCallbackInfo<Value>& args) {
if (!args[0]->IsArrayBuffer()) if (!args[0]->IsArrayBuffer())
return env->ThrowTypeError("argument is not an ArrayBuffer"); return env->ThrowTypeError("argument is not an ArrayBuffer");
Local<ArrayBuffer> ab = args[0].As<ArrayBuffer>(); Local<ArrayBuffer> ab = args[0].As<ArrayBuffer>();
Local<Uint8Array> ui = Uint8Array::New(ab, 0, ab->ByteLength());
size_t ab_length = ab->ByteLength();
size_t offset;
size_t max_length;
CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &offset));
CHECK_NOT_OOB(ParseArrayIndex(args[2], ab_length - offset, &max_length));
if (offset >= ab_length)
return env->ThrowRangeError("'offset' is out of bounds");
if (max_length > ab_length - offset)
return env->ThrowRangeError("'length' is out of bounds");
Local<Uint8Array> ui = Uint8Array::New(ab, offset, max_length);
Maybe<bool> mb = Maybe<bool> mb =
ui->SetPrototype(env->context(), env->buffer_prototype_object()); ui->SetPrototype(env->context(), env->buffer_prototype_object());
if (!mb.FromMaybe(false)) if (!mb.FromMaybe(false))

3
src/node_buffer.h

@ -5,6 +5,9 @@
#include "v8.h" #include "v8.h"
namespace node { namespace node {
extern bool zero_fill_all_buffers;
namespace Buffer { namespace Buffer {
static const unsigned int kMaxLength = static const unsigned int kMaxLength =

2
test/disabled/test-debug-brk-file.js

@ -56,7 +56,7 @@ function debug_client_connect() {
} }
if (msg.headers && Buffer.byteLength(tmpBuf) >= msg.contentLength) { if (msg.headers && Buffer.byteLength(tmpBuf) >= msg.contentLength) {
try { try {
var b = Buffer(tmpBuf); var b = Buffer.from(tmpBuf);
var body = b.toString('utf8', 0, msg.contentLength); var body = b.toString('utf8', 0, msg.contentLength);
tmpBuf = b.toString('utf8', msg.contentLength, b.length); tmpBuf = b.toString('utf8', msg.contentLength, b.length);

3
test/disabled/test-dgram-send-error.js

@ -13,8 +13,7 @@ var assert = require('assert'),
common = require('../common'), common = require('../common'),
dgram = require('dgram'); dgram = require('dgram');
var buf = new Buffer(1024); var buf = Buffer.alloc(1024, 42);
buf.fill(42);
var packetsReceived = 0, var packetsReceived = 0,
packetsSent = 0; packetsSent = 0;

5
test/disabled/test-fs-largefile.js

@ -10,9 +10,9 @@ var path = require('path'),
fs.truncateSync(fd, offset); fs.truncateSync(fd, offset);
assert.equal(fs.statSync(filepath).size, offset); assert.equal(fs.statSync(filepath).size, offset);
var writeBuf = new Buffer(message); var writeBuf = Buffer.from(message);
fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset); fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset);
var readBuf = new Buffer(writeBuf.length); var readBuf = Buffer.allocUnsafe(writeBuf.length);
fs.readSync(fd, readBuf, 0, readBuf.length, offset); fs.readSync(fd, readBuf, 0, readBuf.length, offset);
assert.equal(readBuf.toString(), message); assert.equal(readBuf.toString(), message);
fs.readSync(fd, readBuf, 0, 1, 0); fs.readSync(fd, readBuf, 0, 1, 0);
@ -32,4 +32,3 @@ fs.close(fd);
process.on('exit', function() { process.on('exit', function() {
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
}); });

2
test/disabled/test-sendfd.js

@ -91,7 +91,7 @@ var srv = net.createServer(function(s) {
var str = JSON.stringify(DATA) + '\n'; var str = JSON.stringify(DATA) + '\n';
DATA.ord = DATA.ord + 1; DATA.ord = DATA.ord + 1;
var buf = new buffer.Buffer(str.length); var buf = buffer.Buffer.allocUnsafe(str.length);
buf.write(JSON.stringify(DATA) + '\n', 'utf8'); buf.write(JSON.stringify(DATA) + '\n', 'utf8');
s.write(str, 'utf8', pipeFDs[1]); s.write(str, 'utf8', pipeFDs[1]);

2
test/fixtures/GH-892-request.js

@ -22,7 +22,7 @@ var req = https.request(options, function(res) {
res.resume(); res.resume();
}); });
req.end(new Buffer(bytesExpected)); req.end(Buffer.allocUnsafe(bytesExpected));
process.on('exit', function() { process.on('exit', function() {
assert.ok(gotResponse); assert.ok(gotResponse);

2
test/fixtures/print-chars-from-buffer.js

@ -2,7 +2,7 @@ var assert = require('assert');
var n = parseInt(process.argv[2]); var n = parseInt(process.argv[2]);
var b = new Buffer(n); var b = Buffer.allocUnsafe(n);
for (var i = 0; i < n; i++) { for (var i = 0; i < n; i++) {
b[i] = 100; b[i] = 100;
} }

8
test/internet/test-dgram-broadcast-multi-process.js

@ -9,10 +9,10 @@ const fork = require('child_process').fork;
const LOCAL_BROADCAST_HOST = '255.255.255.255'; const LOCAL_BROADCAST_HOST = '255.255.255.255';
const TIMEOUT = common.platformTimeout(5000); const TIMEOUT = common.platformTimeout(5000);
const messages = [ const messages = [
new Buffer('First message to send'), Buffer.from('First message to send'),
new Buffer('Second message to send'), Buffer.from('Second message to send'),
new Buffer('Third message to send'), Buffer.from('Third message to send'),
new Buffer('Fourth message to send') Buffer.from('Fourth message to send')
]; ];
if (common.inFreeBSDJail) { if (common.inFreeBSDJail) {

8
test/internet/test-dgram-multicast-multi-process.js

@ -6,10 +6,10 @@ const fork = require('child_process').fork;
const LOCAL_BROADCAST_HOST = '224.0.0.114'; const LOCAL_BROADCAST_HOST = '224.0.0.114';
const TIMEOUT = common.platformTimeout(5000); const TIMEOUT = common.platformTimeout(5000);
const messages = [ const messages = [
new Buffer('First message to send'), Buffer.from('First message to send'),
new Buffer('Second message to send'), Buffer.from('Second message to send'),
new Buffer('Third message to send'), Buffer.from('Third message to send'),
new Buffer('Fourth message to send') Buffer.from('Fourth message to send')
]; ];
const workers = {}; const workers = {};
const listeners = 3; const listeners = 3;

2
test/internet/test-dgram-send-cb-quelches-error.js

@ -6,7 +6,7 @@ var dgram = require('dgram');
var dns = require('dns'); var dns = require('dns');
var socket = dgram.createSocket('udp4'); var socket = dgram.createSocket('udp4');
var buffer = new Buffer('gary busey'); var buffer = Buffer.from('gary busey');
dns.setServers([]); dns.setServers([]);

2
test/parallel/test-async-wrap-check-providers.js

@ -81,7 +81,7 @@ net.createServer(function(c) {
}); });
dgram.createSocket('udp4').bind(common.PORT, function() { dgram.createSocket('udp4').bind(common.PORT, function() {
this.send(new Buffer(2), 0, 2, common.PORT, '::', () => { this.send(Buffer.allocUnsafe(2), 0, 2, common.PORT, '::', () => {
this.close(); this.close();
}); });
}); });

1442
test/parallel/test-buffer-alloc.js

File diff suppressed because it is too large

62
test/parallel/test-buffer-arraybuffer.js

@ -9,7 +9,7 @@ const LENGTH = 16;
const ab = new ArrayBuffer(LENGTH); const ab = new ArrayBuffer(LENGTH);
const dv = new DataView(ab); const dv = new DataView(ab);
const ui = new Uint8Array(ab); const ui = new Uint8Array(ab);
const buf = new Buffer(ab); const buf = Buffer.from(ab);
assert.ok(buf instanceof Buffer); assert.ok(buf instanceof Buffer);
@ -42,12 +42,68 @@ assert.throws(function() {
function AB() { } function AB() { }
Object.setPrototypeOf(AB, ArrayBuffer); Object.setPrototypeOf(AB, ArrayBuffer);
Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype); Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype);
new Buffer(new AB()); Buffer.from(new AB());
}, TypeError); }, TypeError);
// write{Double,Float}{LE,BE} with noAssert should not crash, cf. #3766 // write{Double,Float}{LE,BE} with noAssert should not crash, cf. #3766
var b = new Buffer(1); var b = Buffer.allocUnsafe(1);
b.writeFloatLE(11.11, 0, true); b.writeFloatLE(11.11, 0, true);
b.writeFloatBE(11.11, 0, true); b.writeFloatBE(11.11, 0, true);
b.writeDoubleLE(11.11, 0, true); b.writeDoubleLE(11.11, 0, true);
b.writeDoubleBE(11.11, 0, true); b.writeDoubleBE(11.11, 0, true);
// Test the byteOffset and length arguments
{
const ab = new Uint8Array(5);
ab[0] = 1;
ab[1] = 2;
ab[2] = 3;
ab[3] = 4;
ab[4] = 5;
const buf = Buffer.from(ab.buffer, 1, 3);
assert.equal(buf.length, 3);
assert.equal(buf[0], 2);
assert.equal(buf[1], 3);
assert.equal(buf[2], 4);
buf[0] = 9;
assert.equal(ab[1], 9);
assert.throws(() => Buffer.from(ab.buffer, 6), (err) => {
assert(err instanceof RangeError);
assert(/'offset' is out of bounds/.test(err.message));
return true;
});
assert.throws(() => Buffer.from(ab.buffer, 3, 6), (err) => {
assert(err instanceof RangeError);
assert(/'length' is out of bounds/.test(err.message));
return true;
});
}
// Test the deprecated Buffer() version also
{
const ab = new Uint8Array(5);
ab[0] = 1;
ab[1] = 2;
ab[2] = 3;
ab[3] = 4;
ab[4] = 5;
const buf = Buffer(ab.buffer, 1, 3);
assert.equal(buf.length, 3);
assert.equal(buf[0], 2);
assert.equal(buf[1], 3);
assert.equal(buf[2], 4);
buf[0] = 9;
assert.equal(ab[1], 9);
assert.throws(() => Buffer(ab.buffer, 6), (err) => {
assert(err instanceof RangeError);
assert(/'offset' is out of bounds/.test(err.message));
return true;
});
assert.throws(() => Buffer(ab.buffer, 3, 6), (err) => {
assert(err instanceof RangeError);
assert(/'length' is out of bounds/.test(err.message));
return true;
});
}

4
test/parallel/test-buffer-ascii.js

@ -4,7 +4,7 @@ var assert = require('assert');
// ASCII conversion in node.js simply masks off the high bits, // ASCII conversion in node.js simply masks off the high bits,
// it doesn't do transliteration. // it doesn't do transliteration.
assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); assert.equal(Buffer.from('hérité').toString('ascii'), 'hC)ritC)');
// 71 characters, 78 bytes. The ’ character is a triple-byte sequence. // 71 characters, 78 bytes. The ’ character is a triple-byte sequence.
var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + var input = 'C’est, graphiquement, la réunion d’un accent aigu ' +
@ -14,7 +14,7 @@ var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' +
'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' +
'accent grave.'; 'accent grave.';
var buf = Buffer(input); var buf = Buffer.from(input);
for (var i = 0; i < expected.length; ++i) { for (var i = 0; i < expected.length; ++i) {
assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); assert.equal(buf.slice(i).toString('ascii'), expected.slice(i));

4
test/parallel/test-buffer-bytelength.js

@ -11,9 +11,9 @@ assert.equal(Buffer.byteLength({}, 'binary'), 15);
assert.equal(Buffer.byteLength(), 9); assert.equal(Buffer.byteLength(), 9);
// buffer // buffer
var incomplete = new Buffer([0xe4, 0xb8, 0xad, 0xe6, 0x96]); var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]);
assert.equal(Buffer.byteLength(incomplete), 5); assert.equal(Buffer.byteLength(incomplete), 5);
var ascii = new Buffer('abc'); var ascii = Buffer.from('abc');
assert.equal(Buffer.byteLength(ascii), 3); assert.equal(Buffer.byteLength(ascii), 3);
// special case: zero length string // special case: zero length string

8
test/parallel/test-buffer-concat.js

@ -3,9 +3,9 @@ require('../common');
var assert = require('assert'); var assert = require('assert');
var zero = []; var zero = [];
var one = [ new Buffer('asdf') ]; var one = [ Buffer.from('asdf') ];
var long = []; var long = [];
for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); for (var i = 0; i < 10; i++) long.push(Buffer.from('asdf'));
var flatZero = Buffer.concat(zero); var flatZero = Buffer.concat(zero);
var flatOne = Buffer.concat(one); var flatOne = Buffer.concat(one);
@ -22,10 +22,10 @@ assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf')));
assertWrongList(); assertWrongList();
assertWrongList(null); assertWrongList(null);
assertWrongList(new Buffer('hello')); assertWrongList(Buffer.from('hello'));
assertWrongList([42]); assertWrongList([42]);
assertWrongList(['hello', 'world']); assertWrongList(['hello', 'world']);
assertWrongList(['hello', new Buffer('world')]); assertWrongList(['hello', Buffer.from('world')]);
function assertWrongList(value) { function assertWrongList(value) {
assert.throws(function() { assert.throws(function() {

6
test/parallel/test-buffer-fakes.js

@ -11,7 +11,7 @@ Object.setPrototypeOf(FakeBuffer.prototype, Buffer.prototype);
const fb = new FakeBuffer(); const fb = new FakeBuffer();
assert.throws(function() { assert.throws(function() {
new Buffer(fb); Buffer.from(fb);
}, TypeError); }, TypeError);
assert.throws(function() { assert.throws(function() {
@ -19,7 +19,7 @@ assert.throws(function() {
}, TypeError); }, TypeError);
assert.throws(function() { assert.throws(function() {
Buffer.compare(fb, new Buffer(0)); Buffer.compare(fb, Buffer.alloc(0));
}, TypeError); }, TypeError);
assert.throws(function() { assert.throws(function() {
@ -35,7 +35,7 @@ assert.throws(function() {
}, TypeError); }, TypeError);
assert.throws(function() { assert.throws(function() {
fb.equals(new Buffer(0)); fb.equals(Buffer.alloc(0));
}, TypeError); }, TypeError);
assert.throws(function() { assert.throws(function() {

14
test/parallel/test-buffer-fill.js

@ -5,8 +5,8 @@ const assert = require('assert');
const os = require('os'); const os = require('os');
const SIZE = 28; const SIZE = 28;
const buf1 = Buffer(SIZE); const buf1 = Buffer.allocUnsafe(SIZE);
const buf2 = Buffer(SIZE); const buf2 = Buffer.allocUnsafe(SIZE);
// Default encoding // Default encoding
@ -49,7 +49,7 @@ testBufs('\u0222aa', 8, 1, 'utf8');
testBufs('a\u0234b\u0235c\u0236', 4, -1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 4, -1, 'utf8');
testBufs('a\u0234b\u0235c\u0236', 4, 1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 4, 1, 'utf8');
testBufs('a\u0234b\u0235c\u0236', 12, 1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 12, 1, 'utf8');
assert.equal(Buffer(1).fill(0).fill('\u0222')[0], 0xc8); assert.equal(Buffer.allocUnsafe(1).fill(0).fill('\u0222')[0], 0xc8);
// BINARY // BINARY
@ -91,7 +91,7 @@ testBufs('\u0222aa', 8, 1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2');
assert.equal(Buffer(1).fill('\u0222', 'ucs2')[0], assert.equal(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0],
os.endianness() === 'LE' ? 0x22 : 0x02); os.endianness() === 'LE' ? 0x22 : 0x02);
@ -140,13 +140,13 @@ testBufs('Yci0Ysi1Y8i2', 12, 1, 'ucs2');
// Buffer // Buffer
const buf2Fill = Buffer(1).fill(2); const buf2Fill = Buffer.allocUnsafe(1).fill(2);
assert.deepEqual(genBuffer(4, [buf2Fill]), [2, 2, 2, 2]); assert.deepEqual(genBuffer(4, [buf2Fill]), [2, 2, 2, 2]);
assert.deepEqual(genBuffer(4, [buf2Fill, 1]), [0, 2, 2, 2]); assert.deepEqual(genBuffer(4, [buf2Fill, 1]), [0, 2, 2, 2]);
assert.deepEqual(genBuffer(4, [buf2Fill, 1, 3]), [0, 2, 2, 0]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, 3]), [0, 2, 2, 0]);
assert.deepEqual(genBuffer(4, [buf2Fill, 1, 1]), [0, 0, 0, 0]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, 1]), [0, 0, 0, 0]);
assert.deepEqual(genBuffer(4, [buf2Fill, 1, -1]), [0, 0, 0, 0]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, -1]), [0, 0, 0, 0]);
const hexBufFill = Buffer(2).fill(0).fill('0102', 'hex'); const hexBufFill = Buffer.allocUnsafe(2).fill(0).fill('0102', 'hex');
assert.deepEqual(genBuffer(4, [hexBufFill]), [1, 2, 1, 2]); assert.deepEqual(genBuffer(4, [hexBufFill]), [1, 2, 1, 2]);
assert.deepEqual(genBuffer(4, [hexBufFill, 1]), [0, 1, 2, 1]); assert.deepEqual(genBuffer(4, [hexBufFill, 1]), [0, 1, 2, 1]);
assert.deepEqual(genBuffer(4, [hexBufFill, 1, 3]), [0, 1, 2, 0]); assert.deepEqual(genBuffer(4, [hexBufFill, 1, 3]), [0, 1, 2, 0]);
@ -166,7 +166,7 @@ assert.throws(() => buf1.fill('a', 0, 0, 'foo'));
function genBuffer(size, args) { function genBuffer(size, args) {
const b = Buffer(size); const b = Buffer.allocUnsafe(size);
return b.fill(0).fill.apply(b, args); return b.fill(0).fill.apply(b, args);
} }

72
test/parallel/test-buffer-includes.js

@ -4,12 +4,12 @@ const assert = require('assert');
const Buffer = require('buffer').Buffer; const Buffer = require('buffer').Buffer;
const b = new Buffer('abcdef'); const b = Buffer.from('abcdef');
const buf_a = new Buffer('a'); const buf_a = Buffer.from('a');
const buf_bc = new Buffer('bc'); const buf_bc = Buffer.from('bc');
const buf_f = new Buffer('f'); const buf_f = Buffer.from('f');
const buf_z = new Buffer('z'); const buf_z = Buffer.from('z');
const buf_empty = new Buffer(''); const buf_empty = Buffer.from('');
assert(b.includes('a')); assert(b.includes('a'));
assert(!b.includes('a', 1)); assert(!b.includes('a', 1));
@ -71,70 +71,72 @@ assert(b.includes('f', 5));
assert(b.includes('f', -1)); assert(b.includes('f', -1));
assert(!b.includes('f', 6)); assert(!b.includes('f', 6));
assert(b.includes(Buffer('d'), 2)); assert(b.includes(Buffer.from('d'), 2));
assert(b.includes(Buffer('f'), 5)); assert(b.includes(Buffer.from('f'), 5));
assert(b.includes(Buffer('f'), -1)); assert(b.includes(Buffer.from('f'), -1));
assert(!b.includes(Buffer('f'), 6)); assert(!b.includes(Buffer.from('f'), 6));
assert(!Buffer('ff').includes(Buffer('f'), 1, 'ucs2')); assert(!Buffer.from('ff').includes(Buffer.from('f'), 1, 'ucs2'));
// test hex encoding // test hex encoding
assert( assert(
Buffer(b.toString('hex'), 'hex') Buffer.from(b.toString('hex'), 'hex')
.includes('64', 0, 'hex')); .includes('64', 0, 'hex'));
assert( assert(
Buffer(b.toString('hex'), 'hex') Buffer.from(b.toString('hex'), 'hex')
.includes(Buffer('64', 'hex'), 0, 'hex')); .includes(Buffer.from('64', 'hex'), 0, 'hex'));
// test base64 encoding // test base64 encoding
assert( assert(
Buffer(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.includes('ZA==', 0, 'base64')); .includes('ZA==', 0, 'base64'));
assert( assert(
Buffer(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.includes(Buffer('ZA==', 'base64'), 0, 'base64')); .includes(Buffer.from('ZA==', 'base64'), 0, 'base64'));
// test ascii encoding // test ascii encoding
assert( assert(
Buffer(b.toString('ascii'), 'ascii') Buffer.from(b.toString('ascii'), 'ascii')
.includes('d', 0, 'ascii')); .includes('d', 0, 'ascii'));
assert( assert(
Buffer(b.toString('ascii'), 'ascii') Buffer.from(b.toString('ascii'), 'ascii')
.includes(Buffer('d', 'ascii'), 0, 'ascii')); .includes(Buffer.from('d', 'ascii'), 0, 'ascii'));
// test binary encoding // test binary encoding
assert( assert(
Buffer(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.includes('d', 0, 'binary')); .includes('d', 0, 'binary'));
assert( assert(
Buffer(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.includes(Buffer('d', 'binary'), 0, 'binary')); .includes(Buffer.from('d', 'binary'), 0, 'binary'));
// test usc2 encoding // test usc2 encoding
var twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
assert(twoByteString.includes('\u0395', 4, 'ucs2')); assert(twoByteString.includes('\u0395', 4, 'ucs2'));
assert(twoByteString.includes('\u03a3', -4, 'ucs2')); assert(twoByteString.includes('\u03a3', -4, 'ucs2'));
assert(twoByteString.includes('\u03a3', -6, 'ucs2')); assert(twoByteString.includes('\u03a3', -6, 'ucs2'));
assert(twoByteString.includes( assert(twoByteString.includes(
new Buffer('\u03a3', 'ucs2'), -6, 'ucs2')); Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2'));
assert(!twoByteString.includes('\u03a3', -2, 'ucs2')); assert(!twoByteString.includes('\u03a3', -2, 'ucs2'));
const mixedByteStringUcs2 = const mixedByteStringUcs2 =
new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
assert(mixedByteStringUcs2.includes('bc', 0, 'ucs2')); assert(mixedByteStringUcs2.includes('bc', 0, 'ucs2'));
assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2')); assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2'));
assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2')); assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2'));
assert( assert(
6, mixedByteStringUcs2.includes(new Buffer('bc', 'ucs2'), 0, 'ucs2')); 6, mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
assert( assert(
10, mixedByteStringUcs2.includes(new Buffer('\u03a3', 'ucs2'), 0, 'ucs2')); 10, mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'),
0, 'ucs2'));
assert( assert(
-1, mixedByteStringUcs2.includes(new Buffer('\u0396', 'ucs2'), 0, 'ucs2')); -1, mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'),
0, 'ucs2'));
twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
// Test single char pattern // Test single char pattern
assert(twoByteString.includes('\u039a', 0, 'ucs2')); assert(twoByteString.includes('\u039a', 0, 'ucs2'));
@ -150,7 +152,7 @@ assert(twoByteString.includes('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma');
assert(twoByteString.includes('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma'); assert(twoByteString.includes('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma');
assert(twoByteString.includes('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); assert(twoByteString.includes('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
const mixedByteStringUtf8 = new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395'); const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
assert(mixedByteStringUtf8.includes('bc')); assert(mixedByteStringUtf8.includes('bc'));
assert(mixedByteStringUtf8.includes('bc', 5)); assert(mixedByteStringUtf8.includes('bc', 5));
assert(mixedByteStringUtf8.includes('bc', -8)); assert(mixedByteStringUtf8.includes('bc', -8));
@ -165,7 +167,7 @@ for (let i = 66; i < 76; i++) { // from 'B' to 'K'
longString = longString + String.fromCharCode(i) + longString; longString = longString + String.fromCharCode(i) + longString;
} }
const longBufferString = new Buffer(longString); const longBufferString = Buffer.from(longString);
// pattern of 15 chars, repeated every 16 chars in long // pattern of 15 chars, repeated every 16 chars in long
var pattern = 'ABACABADABACABA'; var pattern = 'ABACABADABACABA';
@ -181,7 +183,7 @@ assert(longBufferString.includes(pattern), 'Long JABACABA..., First J');
assert(longBufferString.includes(pattern, 512), 'Long JABACABA..., Second J'); assert(longBufferString.includes(pattern, 512), 'Long JABACABA..., Second J');
// Search for a non-ASCII string in a pure ASCII string. // Search for a non-ASCII string in a pure ASCII string.
const asciiString = new Buffer( const asciiString = Buffer.from(
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
assert(!asciiString.includes('\x2061')); assert(!asciiString.includes('\x2061'));
assert(asciiString.includes('leb', 0)); assert(asciiString.includes('leb', 0));
@ -190,8 +192,8 @@ assert(asciiString.includes('leb', 0));
const allCodePoints = []; const allCodePoints = [];
for (let i = 0; i < 65536; i++) allCodePoints[i] = i; for (let i = 0; i < 65536; i++) allCodePoints[i] = i;
const allCharsString = String.fromCharCode.apply(String, allCodePoints); const allCharsString = String.fromCharCode.apply(String, allCodePoints);
const allCharsBufferUtf8 = new Buffer(allCharsString); const allCharsBufferUtf8 = Buffer.from(allCharsString);
const allCharsBufferUcs2 = new Buffer(allCharsString, 'ucs2'); const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2');
// Search for string long enough to trigger complex search with ASCII pattern // Search for string long enough to trigger complex search with ASCII pattern
// and UC16 subject. // and UC16 subject.

82
test/parallel/test-buffer-indexof.js

@ -4,12 +4,12 @@ var assert = require('assert');
var Buffer = require('buffer').Buffer; var Buffer = require('buffer').Buffer;
var b = new Buffer('abcdef'); var b = Buffer.from('abcdef');
var buf_a = new Buffer('a'); var buf_a = Buffer.from('a');
var buf_bc = new Buffer('bc'); var buf_bc = Buffer.from('bc');
var buf_f = new Buffer('f'); var buf_f = Buffer.from('f');
var buf_z = new Buffer('z'); var buf_z = Buffer.from('z');
var buf_empty = new Buffer(''); var buf_empty = Buffer.from('');
assert.equal(b.indexOf('a'), 0); assert.equal(b.indexOf('a'), 0);
assert.equal(b.indexOf('a', 1), -1); assert.equal(b.indexOf('a', 1), -1);
@ -71,86 +71,86 @@ assert.equal(b.indexOf('f', 5), 5);
assert.equal(b.indexOf('f', -1), 5); assert.equal(b.indexOf('f', -1), 5);
assert.equal(b.indexOf('f', 6), -1); assert.equal(b.indexOf('f', 6), -1);
assert.equal(b.indexOf(Buffer('d'), 2), 3); assert.equal(b.indexOf(Buffer.from('d'), 2), 3);
assert.equal(b.indexOf(Buffer('f'), 5), 5); assert.equal(b.indexOf(Buffer.from('f'), 5), 5);
assert.equal(b.indexOf(Buffer('f'), -1), 5); assert.equal(b.indexOf(Buffer.from('f'), -1), 5);
assert.equal(b.indexOf(Buffer('f'), 6), -1); assert.equal(b.indexOf(Buffer.from('f'), 6), -1);
assert.equal(Buffer('ff').indexOf(Buffer('f'), 1, 'ucs2'), -1); assert.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1);
// test hex encoding // test hex encoding
assert.equal( assert.equal(
Buffer(b.toString('hex'), 'hex') Buffer.from(b.toString('hex'), 'hex')
.indexOf('64', 0, 'hex'), 3); .indexOf('64', 0, 'hex'), 3);
assert.equal( assert.equal(
Buffer(b.toString('hex'), 'hex') Buffer.from(b.toString('hex'), 'hex')
.indexOf(Buffer('64', 'hex'), 0, 'hex'), 3); .indexOf(Buffer.from('64', 'hex'), 0, 'hex'), 3);
// test base64 encoding // test base64 encoding
assert.equal( assert.equal(
Buffer(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.indexOf('ZA==', 0, 'base64'), 3); .indexOf('ZA==', 0, 'base64'), 3);
assert.equal( assert.equal(
Buffer(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.indexOf(Buffer('ZA==', 'base64'), 0, 'base64'), 3); .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), 3);
// test ascii encoding // test ascii encoding
assert.equal( assert.equal(
Buffer(b.toString('ascii'), 'ascii') Buffer.from(b.toString('ascii'), 'ascii')
.indexOf('d', 0, 'ascii'), 3); .indexOf('d', 0, 'ascii'), 3);
assert.equal( assert.equal(
Buffer(b.toString('ascii'), 'ascii') Buffer.from(b.toString('ascii'), 'ascii')
.indexOf(Buffer('d', 'ascii'), 0, 'ascii'), 3); .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), 3);
// test binary encoding // test binary encoding
assert.equal( assert.equal(
Buffer(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.indexOf('d', 0, 'binary'), 3); .indexOf('d', 0, 'binary'), 3);
assert.equal( assert.equal(
Buffer(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.indexOf(Buffer('d', 'binary'), 0, 'binary'), 3); .indexOf(Buffer.from('d', 'binary'), 0, 'binary'), 3);
assert.equal( assert.equal(
Buffer('aa\u00e8aa', 'binary') Buffer.from('aa\u00e8aa', 'binary')
.indexOf('\u00e8', 'binary'), 2); .indexOf('\u00e8', 'binary'), 2);
assert.equal( assert.equal(
Buffer('\u00e8', 'binary') Buffer.from('\u00e8', 'binary')
.indexOf('\u00e8', 'binary'), 0); .indexOf('\u00e8', 'binary'), 0);
assert.equal( assert.equal(
Buffer('\u00e8', 'binary') Buffer.from('\u00e8', 'binary')
.indexOf(Buffer('\u00e8', 'binary'), 'binary'), 0); .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), 0);
// test optional offset with passed encoding // test optional offset with passed encoding
assert.equal(new Buffer('aaaa0').indexOf('30', 'hex'), 4); assert.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4);
assert.equal(new Buffer('aaaa00a').indexOf('3030', 'hex'), 4); assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4);
{ {
// test usc2 encoding // test usc2 encoding
const twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')); assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2'));
assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')); assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2'));
assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')); assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2'));
assert.equal(4, twoByteString.indexOf( assert.equal(4, twoByteString.indexOf(
new Buffer('\u03a3', 'ucs2'), -6, 'ucs2')); Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2'));
assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2'));
} }
var mixedByteStringUcs2 = var mixedByteStringUcs2 =
new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2'));
assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2'));
assert.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')); assert.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2'));
assert.equal( assert.equal(
6, mixedByteStringUcs2.indexOf(new Buffer('bc', 'ucs2'), 0, 'ucs2')); 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
assert.equal( assert.equal(
10, mixedByteStringUcs2.indexOf(new Buffer('\u03a3', 'ucs2'), 0, 'ucs2')); 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2'));
assert.equal( assert.equal(
-1, mixedByteStringUcs2.indexOf(new Buffer('\u0396', 'ucs2'), 0, 'ucs2')); -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2'));
{ {
const twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
// Test single char pattern // Test single char pattern
assert.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')); assert.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2'));
@ -171,7 +171,7 @@ assert.equal(
6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
} }
var mixedByteStringUtf8 = new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395'); var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
assert.equal(5, mixedByteStringUtf8.indexOf('bc')); assert.equal(5, mixedByteStringUtf8.indexOf('bc'));
assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5)); assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5));
assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8)); assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8));
@ -186,7 +186,7 @@ for (let i = 66; i < 76; i++) { // from 'B' to 'K'
longString = longString + String.fromCharCode(i) + longString; longString = longString + String.fromCharCode(i) + longString;
} }
var longBufferString = new Buffer(longString); var longBufferString = Buffer.from(longString);
// pattern of 15 chars, repeated every 16 chars in long // pattern of 15 chars, repeated every 16 chars in long
var pattern = 'ABACABADABACABA'; var pattern = 'ABACABADABACABA';
@ -205,7 +205,7 @@ assert.equal(
1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J');
// Search for a non-ASCII string in a pure ASCII string. // Search for a non-ASCII string in a pure ASCII string.
var asciiString = new Buffer( var asciiString = Buffer.from(
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
assert.equal(-1, asciiString.indexOf('\x2061')); assert.equal(-1, asciiString.indexOf('\x2061'));
assert.equal(3, asciiString.indexOf('leb', 0)); assert.equal(3, asciiString.indexOf('leb', 0));
@ -214,8 +214,8 @@ assert.equal(3, asciiString.indexOf('leb', 0));
var allCodePoints = []; var allCodePoints = [];
for (let i = 0; i < 65536; i++) allCodePoints[i] = i; for (let i = 0; i < 65536; i++) allCodePoints[i] = i;
var allCharsString = String.fromCharCode.apply(String, allCodePoints); var allCharsString = String.fromCharCode.apply(String, allCodePoints);
var allCharsBufferUtf8 = new Buffer(allCharsString); var allCharsBufferUtf8 = Buffer.from(allCharsString);
var allCharsBufferUcs2 = new Buffer(allCharsString, 'ucs2'); var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2');
// Search for string long enough to trigger complex search with ASCII pattern // Search for string long enough to trigger complex search with ASCII pattern
// and UC16 subject. // and UC16 subject.

8
test/parallel/test-buffer-inspect.js

@ -8,10 +8,10 @@ var buffer = require('buffer');
buffer.INSPECT_MAX_BYTES = 2; buffer.INSPECT_MAX_BYTES = 2;
var b = new Buffer(4); var b = Buffer.allocUnsafe(4);
b.fill('1234'); b.fill('1234');
var s = new buffer.SlowBuffer(4); var s = buffer.SlowBuffer(4);
s.fill('1234'); s.fill('1234');
var expected = '<Buffer 31 32 ... >'; var expected = '<Buffer 31 32 ... >';
@ -19,10 +19,10 @@ var expected = '<Buffer 31 32 ... >';
assert.strictEqual(util.inspect(b), expected); assert.strictEqual(util.inspect(b), expected);
assert.strictEqual(util.inspect(s), expected); assert.strictEqual(util.inspect(s), expected);
b = new Buffer(2); b = Buffer.allocUnsafe(2);
b.fill('12'); b.fill('12');
s = new buffer.SlowBuffer(2); s = buffer.SlowBuffer(2);
s.fill('12'); s.fill('12');
expected = '<Buffer 31 32>'; expected = '<Buffer 31 32>';

2
test/parallel/test-buffer-iterator.js

@ -2,7 +2,7 @@
require('../common'); require('../common');
var assert = require('assert'); var assert = require('assert');
var buffer = new Buffer([1, 2, 3, 4, 5]); var buffer = Buffer.from([1, 2, 3, 4, 5]);
var arr; var arr;
var b; var b;

14
test/parallel/test-buffer-safe-unsafe.js

@ -0,0 +1,14 @@
'use strict';
require('../common');
const assert = require('assert');
const safe = Buffer.alloc(10);
function isZeroFilled(buf) {
for (let n = 0; n < buf.length; n++)
if (buf[n] > 0) return false;
return true;
}
assert(isZeroFilled(safe));

11
test/parallel/test-buffer-slow.js

@ -9,7 +9,7 @@ const SlowBuffer = buffer.SlowBuffer;
const ones = [1, 1, 1, 1]; const ones = [1, 1, 1, 1];
// should create a Buffer // should create a Buffer
let sb = new SlowBuffer(4); let sb = SlowBuffer(4);
assert(sb instanceof Buffer); assert(sb instanceof Buffer);
assert.strictEqual(sb.length, 4); assert.strictEqual(sb.length, 4);
sb.fill(1); sb.fill(1);
@ -28,7 +28,8 @@ assert.deepEqual(sb, ones);
// should work with edge cases // should work with edge cases
assert.strictEqual(SlowBuffer(0).length, 0); assert.strictEqual(SlowBuffer(0).length, 0);
try { try {
assert.strictEqual(SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength); assert.strictEqual(
SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength);
} catch (e) { } catch (e) {
assert.equal(e.message, 'Array buffer allocation failed'); assert.equal(e.message, 'Array buffer allocation failed');
} }
@ -45,11 +46,11 @@ assert.strictEqual(SlowBuffer('string').length, 0);
// should throw with invalid length // should throw with invalid length
assert.throws(function() { assert.throws(function() {
new SlowBuffer(Infinity); SlowBuffer(Infinity);
}, 'invalid Buffer length'); }, 'invalid Buffer length');
assert.throws(function() { assert.throws(function() {
new SlowBuffer(-1); SlowBuffer(-1);
}, 'invalid Buffer length'); }, 'invalid Buffer length');
assert.throws(function() { assert.throws(function() {
new SlowBuffer(buffer.kMaxLength + 1); SlowBuffer(buffer.kMaxLength + 1);
}, 'invalid Buffer length'); }, 'invalid Buffer length');

32
test/parallel/test-buffer-zero-fill-cli.js

@ -0,0 +1,32 @@
'use strict';
// Flags: --zero-fill-buffers
// when using --zero-fill-buffers, every Buffer and SlowBuffer
// instance must be zero filled upon creation
require('../common');
const SlowBuffer = require('buffer').SlowBuffer;
const assert = require('assert');
function isZeroFilled(buf) {
for (let n = 0; n < buf.length; n++)
if (buf[n] > 0) return false;
return true;
}
// This can be somewhat unreliable because the
// allocated memory might just already happen to
// contain all zeroes. The test is run multiple
// times to improve the reliability.
for (let i = 0; i < 50; i++) {
const bufs = [
Buffer.alloc(20),
Buffer.allocUnsafe(20),
SlowBuffer(20),
Buffer(20),
new SlowBuffer(20)
];
for (const buf of bufs) {
assert(isZeroFilled(buf));
}
}

2
test/parallel/test-buffer-zero-fill-reset.js

@ -13,7 +13,7 @@ function testUint8Array(ui) {
for (let i = 0; i < 100; i++) { for (let i = 0; i < 100; i++) {
new Buffer(0); Buffer.alloc(0);
const ui = new Uint8Array(65); const ui = new Uint8Array(65);
assert.ok(testUint8Array(ui), 'Uint8Array is not zero-filled'); assert.ok(testUint8Array(ui), 'Uint8Array is not zero-filled');
} }

89
test/parallel/test-buffer.js

@ -24,7 +24,7 @@ for (let i = 0; i < 1024; i++) {
assert.strictEqual(i % 256, b[i]); assert.strictEqual(i % 256, b[i]);
} }
var c = new Buffer(512); var c = Buffer(512);
console.log('c.length == %d', c.length); console.log('c.length == %d', c.length);
assert.strictEqual(512, c.length); assert.strictEqual(512, c.length);
@ -177,7 +177,7 @@ Buffer(8).fill('');
} }
// copy string longer than buffer length (failure will segfault) // copy string longer than buffer length (failure will segfault)
var bb = new Buffer(10); var bb = Buffer(10);
bb.fill('hello crazy world'); bb.fill('hello crazy world');
@ -236,7 +236,7 @@ assert.strictEqual('Unknown encoding: invalid', caught_error.message);
new Buffer(''); new Buffer('');
new Buffer('', 'ascii'); new Buffer('', 'ascii');
new Buffer('', 'binary'); new Buffer('', 'binary');
new Buffer(0); Buffer(0);
// try to write a 0-length string beyond the end of b // try to write a 0-length string beyond the end of b
assert.throws(function() { assert.throws(function() {
@ -259,14 +259,14 @@ assert.throws(function() {
}, RangeError); }, RangeError);
// try to copy 0 bytes worth of data into an empty buffer // try to copy 0 bytes worth of data into an empty buffer
b.copy(new Buffer(0), 0, 0, 0); b.copy(Buffer(0), 0, 0, 0);
// try to copy 0 bytes past the end of the target buffer // try to copy 0 bytes past the end of the target buffer
b.copy(new Buffer(0), 1, 1, 1); b.copy(Buffer(0), 1, 1, 1);
b.copy(new Buffer(1), 1, 1, 1); b.copy(Buffer(1), 1, 1, 1);
// try to copy 0 bytes from past the end of the source buffer // try to copy 0 bytes from past the end of the source buffer
b.copy(new Buffer(1), 0, 2048, 2048); b.copy(Buffer(1), 0, 2048, 2048);
const rangeBuffer = new Buffer('abc'); const rangeBuffer = new Buffer('abc');
@ -750,7 +750,7 @@ for (let i = 0; i < 256; i++) {
function buildBuffer(data) { function buildBuffer(data) {
if (Array.isArray(data)) { if (Array.isArray(data)) {
var buffer = new Buffer(data.length); var buffer = Buffer(data.length);
data.forEach(function(v, k) { data.forEach(function(v, k) {
buffer[k] = v; buffer[k] = v;
}); });
@ -1035,53 +1035,53 @@ Buffer(Buffer(0), 0, 0);
// issue GH-4331 // issue GH-4331
assert.throws(function() { assert.throws(function() {
new Buffer(0xFFFFFFFF); Buffer(0xFFFFFFFF);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
new Buffer(0xFFFFFFFFF); Buffer(0xFFFFFFFFF);
}, RangeError); }, RangeError);
// attempt to overflow buffers, similar to previous bug in array buffers // attempt to overflow buffers, similar to previous bug in array buffers
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.readFloatLE(0xffffffff); buf.readFloatLE(0xffffffff);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.writeFloatLE(0.0, 0xffffffff); buf.writeFloatLE(0.0, 0xffffffff);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.readFloatLE(0xffffffff); buf.readFloatLE(0xffffffff);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.writeFloatLE(0.0, 0xffffffff); buf.writeFloatLE(0.0, 0xffffffff);
}, RangeError); }, RangeError);
// ensure negative values can't get past offset // ensure negative values can't get past offset
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.readFloatLE(-1); buf.readFloatLE(-1);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.writeFloatLE(0.0, -1); buf.writeFloatLE(0.0, -1);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.readFloatLE(-1); buf.readFloatLE(-1);
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
var buf = new Buffer(8); var buf = Buffer(8);
buf.writeFloatLE(0.0, -1); buf.writeFloatLE(0.0, -1);
}, RangeError); }, RangeError);
@ -1160,92 +1160,92 @@ assert.throws(function() {
// test for common write(U)IntLE/BE // test for common write(U)IntLE/BE
(function() { (function() {
var buf = new Buffer(3); var buf = Buffer(3);
buf.writeUIntLE(0x123456, 0, 3); buf.writeUIntLE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 3), 0x123456); assert.equal(buf.readUIntLE(0, 3), 0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeUIntBE(0x123456, 0, 3); buf.writeUIntBE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
assert.equal(buf.readUIntBE(0, 3), 0x123456); assert.equal(buf.readUIntBE(0, 3), 0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntLE(0x123456, 0, 3); buf.writeIntLE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readIntLE(0, 3), 0x123456); assert.equal(buf.readIntLE(0, 3), 0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntBE(0x123456, 0, 3); buf.writeIntBE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
assert.equal(buf.readIntBE(0, 3), 0x123456); assert.equal(buf.readIntBE(0, 3), 0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntLE(-0x123456, 0, 3); buf.writeIntLE(-0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]);
assert.equal(buf.readIntLE(0, 3), -0x123456); assert.equal(buf.readIntLE(0, 3), -0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntBE(-0x123456, 0, 3); buf.writeIntBE(-0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]);
assert.equal(buf.readIntBE(0, 3), -0x123456); assert.equal(buf.readIntBE(0, 3), -0x123456);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntLE(-0x123400, 0, 3); buf.writeIntLE(-0x123400, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]); assert.deepEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]);
assert.equal(buf.readIntLE(0, 3), -0x123400); assert.equal(buf.readIntLE(0, 3), -0x123400);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntBE(-0x123400, 0, 3); buf.writeIntBE(-0x123400, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]); assert.deepEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]);
assert.equal(buf.readIntBE(0, 3), -0x123400); assert.equal(buf.readIntBE(0, 3), -0x123400);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntLE(-0x120000, 0, 3); buf.writeIntLE(-0x120000, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0xee]); assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0xee]);
assert.equal(buf.readIntLE(0, 3), -0x120000); assert.equal(buf.readIntLE(0, 3), -0x120000);
buf = new Buffer(3); buf = Buffer(3);
buf.writeIntBE(-0x120000, 0, 3); buf.writeIntBE(-0x120000, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xee, 0x00, 0x00]); assert.deepEqual(buf.toJSON().data, [0xee, 0x00, 0x00]);
assert.equal(buf.readIntBE(0, 3), -0x120000); assert.equal(buf.readIntBE(0, 3), -0x120000);
buf = new Buffer(5); buf = Buffer(5);
buf.writeUIntLE(0x1234567890, 0, 5); buf.writeUIntLE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 5), 0x1234567890); assert.equal(buf.readUIntLE(0, 5), 0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeUIntBE(0x1234567890, 0, 5); buf.writeUIntBE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
assert.equal(buf.readUIntBE(0, 5), 0x1234567890); assert.equal(buf.readUIntBE(0, 5), 0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntLE(0x1234567890, 0, 5); buf.writeIntLE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
assert.equal(buf.readIntLE(0, 5), 0x1234567890); assert.equal(buf.readIntLE(0, 5), 0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntBE(0x1234567890, 0, 5); buf.writeIntBE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
assert.equal(buf.readIntBE(0, 5), 0x1234567890); assert.equal(buf.readIntBE(0, 5), 0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntLE(-0x1234567890, 0, 5); buf.writeIntLE(-0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]);
assert.equal(buf.readIntLE(0, 5), -0x1234567890); assert.equal(buf.readIntLE(0, 5), -0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntBE(-0x1234567890, 0, 5); buf.writeIntBE(-0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]);
assert.equal(buf.readIntBE(0, 5), -0x1234567890); assert.equal(buf.readIntBE(0, 5), -0x1234567890);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntLE(-0x0012000000, 0, 5); buf.writeIntLE(-0x0012000000, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]); assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]);
assert.equal(buf.readIntLE(0, 5), -0x0012000000); assert.equal(buf.readIntLE(0, 5), -0x0012000000);
buf = new Buffer(5); buf = Buffer(5);
buf.writeIntBE(-0x0012000000, 0, 5); buf.writeIntBE(-0x0012000000, 0, 5);
assert.deepEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.deepEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]);
assert.equal(buf.readIntBE(0, 5), -0x0012000000); assert.equal(buf.readIntBE(0, 5), -0x0012000000);
@ -1330,7 +1330,7 @@ assert.throws(function() {
}, RangeError); }, RangeError);
assert.throws(function() { assert.throws(function() {
new SlowBuffer((-1 >>> 0) + 1); SlowBuffer((-1 >>> 0) + 1);
}, RangeError); }, RangeError);
if (common.hasCrypto) { if (common.hasCrypto) {
@ -1372,17 +1372,17 @@ if (common.hasCrypto) {
} }
assert.throws(function() { assert.throws(function() {
var b = new Buffer(1); var b = Buffer(1);
Buffer.compare(b, 'abc'); Buffer.compare(b, 'abc');
}); });
assert.throws(function() { assert.throws(function() {
var b = new Buffer(1); var b = Buffer(1);
Buffer.compare('abc', b); Buffer.compare('abc', b);
}); });
assert.throws(function() { assert.throws(function() {
var b = new Buffer(1); var b = Buffer(1);
b.compare('abc'); b.compare('abc');
}); });
@ -1400,7 +1400,7 @@ assert.throws(function() {
} }
assert.throws(function() { assert.throws(function() {
var b = new Buffer(1); var b = Buffer(1);
b.equals('abc'); b.equals('abc');
}); });
@ -1417,13 +1417,16 @@ assert.throws(function() {
Buffer(10).copy(); Buffer(10).copy();
}); });
const regErrorMsg = new RegExp('First argument must be a string, Buffer, ' +
'ArrayBuffer, Array, or array-like object.');
assert.throws(function() { assert.throws(function() {
new Buffer(); new Buffer();
}, /Must start with number, buffer, array or string/); }, regErrorMsg);
assert.throws(function() { assert.throws(function() {
new Buffer(null); new Buffer(null);
}, /Must start with number, buffer, array or string/); }, regErrorMsg);
// Test prototype getters don't throw // Test prototype getters don't throw

2
test/parallel/test-child-process-fork-dgram.js

@ -45,7 +45,7 @@ if (process.argv[2] === 'child') {
var client = dgram.createSocket('udp4'); var client = dgram.createSocket('udp4');
var child = fork(__filename, ['child']); var child = fork(__filename, ['child']);
var msg = new Buffer('Some bytes'); var msg = Buffer.from('Some bytes');
var childGotMessage = false; var childGotMessage = false;
var parentGotMessage = false; var parentGotMessage = false;

8
test/parallel/test-child-process-spawnsync-input.js

@ -9,8 +9,8 @@ const msgOut = 'this is stdout';
const msgErr = 'this is stderr'; const msgErr = 'this is stderr';
// this is actually not os.EOL? // this is actually not os.EOL?
const msgOutBuf = new Buffer(msgOut + '\n'); const msgOutBuf = Buffer.from(msgOut + '\n');
const msgErrBuf = new Buffer(msgErr + '\n'); const msgErrBuf = Buffer.from(msgErr + '\n');
const args = [ const args = [
'-e', '-e',
@ -71,14 +71,14 @@ assert.strictEqual(ret.stdout.toString('utf8'), options.input);
assert.strictEqual(ret.stderr.toString('utf8'), ''); assert.strictEqual(ret.stderr.toString('utf8'), '');
options = { options = {
input: new Buffer('hello world') input: Buffer.from('hello world')
}; };
ret = spawnSync('cat', [], options); ret = spawnSync('cat', [], options);
checkSpawnSyncRet(ret); checkSpawnSyncRet(ret);
assert.deepEqual(ret.stdout, options.input); assert.deepEqual(ret.stdout, options.input);
assert.deepEqual(ret.stderr, new Buffer('')); assert.deepEqual(ret.stderr, Buffer.from(''));
verifyBufOutput(spawnSync(process.execPath, args)); verifyBufOutput(spawnSync(process.execPath, args));

2
test/parallel/test-child-process-spawnsync-maxbuf.js

@ -7,7 +7,7 @@ const spawnSync = require('child_process').spawnSync;
const msgOut = 'this is stdout'; const msgOut = 'this is stdout';
// This is actually not os.EOL? // This is actually not os.EOL?
const msgOutBuf = new Buffer(msgOut + '\n'); const msgOutBuf = Buffer.from(msgOut + '\n');
const args = [ const args = [
'-e', '-e',

6
test/parallel/test-child-process-stdio-big-write-end.js

@ -29,15 +29,13 @@ function parent() {
// Write until the buffer fills up. // Write until the buffer fills up.
do { do {
var buf = new Buffer(BUFSIZE); var buf = Buffer.alloc(BUFSIZE, '.');
buf.fill('.');
sent += BUFSIZE; sent += BUFSIZE;
} while (child.stdin.write(buf)); } while (child.stdin.write(buf));
// then write a bunch more times. // then write a bunch more times.
for (var i = 0; i < 100; i++) { for (var i = 0; i < 100; i++) {
const buf = new Buffer(BUFSIZE); const buf = Buffer.alloc(BUFSIZE, '.');
buf.fill('.');
sent += BUFSIZE; sent += BUFSIZE;
child.stdin.write(buf); child.stdin.write(buf);
} }

2
test/parallel/test-cluster-dgram-1.js

@ -33,7 +33,7 @@ function master() {
return; return;
// Start sending messages. // Start sending messages.
var buf = new Buffer('hello world'); var buf = Buffer.from('hello world');
var socket = dgram.createSocket('udp4'); var socket = dgram.createSocket('udp4');
var sent = 0; var sent = 0;
doSend(); doSend();

2
test/parallel/test-cluster-dgram-2.js

@ -51,7 +51,7 @@ function master() {
function worker() { function worker() {
// Create udp socket and send packets to master. // Create udp socket and send packets to master.
var socket = dgram.createSocket('udp4'); var socket = dgram.createSocket('udp4');
var buf = new Buffer('hello world'); var buf = Buffer.from('hello world');
// This test is intended to exercise the cluster binding of udp sockets, but // This test is intended to exercise the cluster binding of udp sockets, but
// since sockets aren't clustered when implicitly bound by at first call of // since sockets aren't clustered when implicitly bound by at first call of

26
test/parallel/test-crypto-authenticated.js

@ -62,9 +62,9 @@ for (var i in TEST_CASES) {
(function() { (function() {
var encrypt = crypto.createCipheriv(test.algo, var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
if (test.aad) if (test.aad)
encrypt.setAAD(new Buffer(test.aad, 'hex')); encrypt.setAAD(Buffer.from(test.aad, 'hex'));
var hex = encrypt.update(test.plain, 'ascii', 'hex'); var hex = encrypt.update(test.plain, 'ascii', 'hex');
hex += encrypt.final('hex'); hex += encrypt.final('hex');
var auth_tag = encrypt.getAuthTag(); var auth_tag = encrypt.getAuthTag();
@ -77,10 +77,10 @@ for (var i in TEST_CASES) {
(function() { (function() {
var decrypt = crypto.createDecipheriv(test.algo, var decrypt = crypto.createDecipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
decrypt.setAuthTag(new Buffer(test.tag, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
if (test.aad) if (test.aad)
decrypt.setAAD(new Buffer(test.aad, 'hex')); decrypt.setAAD(Buffer.from(test.aad, 'hex'));
var msg = decrypt.update(test.ct, 'hex', 'ascii'); var msg = decrypt.update(test.ct, 'hex', 'ascii');
if (!test.tampered) { if (!test.tampered) {
msg += decrypt.final('ascii'); msg += decrypt.final('ascii');
@ -100,7 +100,7 @@ for (var i in TEST_CASES) {
} else { } else {
var encrypt = crypto.createCipher(test.algo, test.password); var encrypt = crypto.createCipher(test.algo, test.password);
if (test.aad) if (test.aad)
encrypt.setAAD(new Buffer(test.aad, 'hex')); encrypt.setAAD(Buffer.from(test.aad, 'hex'));
var hex = encrypt.update(test.plain, 'ascii', 'hex'); var hex = encrypt.update(test.plain, 'ascii', 'hex');
hex += encrypt.final('hex'); hex += encrypt.final('hex');
var auth_tag = encrypt.getAuthTag(); var auth_tag = encrypt.getAuthTag();
@ -120,9 +120,9 @@ for (var i in TEST_CASES) {
/not supported in FIPS mode/); /not supported in FIPS mode/);
} else { } else {
var decrypt = crypto.createDecipher(test.algo, test.password); var decrypt = crypto.createDecipher(test.algo, test.password);
decrypt.setAuthTag(new Buffer(test.tag, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
if (test.aad) if (test.aad)
decrypt.setAAD(new Buffer(test.aad, 'hex')); decrypt.setAAD(Buffer.from(test.aad, 'hex'));
var msg = decrypt.update(test.ct, 'hex', 'ascii'); var msg = decrypt.update(test.ct, 'hex', 'ascii');
if (!test.tampered) { if (!test.tampered) {
msg += decrypt.final('ascii'); msg += decrypt.final('ascii');
@ -149,13 +149,13 @@ for (var i in TEST_CASES) {
encrypt.final(); encrypt.final();
assert.throws(function() { encrypt.getAuthTag(); }, / state/); assert.throws(function() { encrypt.getAuthTag(); }, / state/);
assert.throws(function() { assert.throws(function() {
encrypt.setAAD(new Buffer('123', 'ascii')); }, / state/); encrypt.setAAD(Buffer.from('123', 'ascii')); }, / state/);
})(); })();
(function() { (function() {
// trying to get tag before inputting all data: // trying to get tag before inputting all data:
var encrypt = crypto.createCipheriv(test.algo, var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
encrypt.update('blah', 'ascii'); encrypt.update('blah', 'ascii');
assert.throws(function() { encrypt.getAuthTag(); }, / state/); assert.throws(function() { encrypt.getAuthTag(); }, / state/);
})(); })();
@ -163,15 +163,15 @@ for (var i in TEST_CASES) {
(function() { (function() {
// trying to set tag on encryption object: // trying to set tag on encryption object:
var encrypt = crypto.createCipheriv(test.algo, var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
assert.throws(function() { assert.throws(function() {
encrypt.setAuthTag(new Buffer(test.tag, 'hex')); }, / state/); encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/);
})(); })();
(function() { (function() {
// trying to read tag from decryption object: // trying to read tag from decryption object:
var decrypt = crypto.createDecipheriv(test.algo, var decrypt = crypto.createDecipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
assert.throws(function() { decrypt.getAuthTag(); }, / state/); assert.throws(function() { decrypt.getAuthTag(); }, / state/);
})(); })();
} }

74
test/parallel/test-crypto-binary-default.js

@ -55,8 +55,8 @@ assert.equal(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC');
// Test HMAC-SHA-* (rfc 4231 Test Cases) // Test HMAC-SHA-* (rfc 4231 Test Cases)
var rfc4231 = [ var rfc4231 = [
{ {
key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
data: new Buffer('4869205468657265', 'hex'), // 'Hi There' data: Buffer.from('4869205468657265', 'hex'), // 'Hi There'
hmac: { hmac: {
sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22',
sha256: sha256:
@ -72,8 +72,8 @@ var rfc4231 = [
} }
}, },
{ {
key: new Buffer('4a656665', 'hex'), // 'Jefe' key: Buffer.from('4a656665', 'hex'), // 'Jefe'
data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' +
'96e673f', 'hex'), // 'what do ya want for nothing?' '96e673f', 'hex'), // 'what do ya want for nothing?'
hmac: { hmac: {
sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44',
@ -90,8 +90,8 @@ var rfc4231 = [
} }
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
'hex'), 'hex'),
hmac: { hmac: {
@ -109,9 +109,9 @@ var rfc4231 = [
} }
}, },
{ {
key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
'hex'), 'hex'),
data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
'hex'), 'hex'),
hmac: { hmac: {
@ -130,9 +130,9 @@ var rfc4231 = [
}, },
{ {
key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
// 'Test With Truncation' // 'Test With Truncation'
data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'),
hmac: { hmac: {
sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8',
sha256: 'a3b6167473100ee06e0c796c2955552b', sha256: 'a3b6167473100ee06e0c796c2955552b',
@ -142,14 +142,14 @@ var rfc4231 = [
truncate: true truncate: true
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaa', 'hex'), 'aaaaaaaaaaaa', 'hex'),
// 'Test Using Larger Than Block-Size Key - Hash Key First' // 'Test Using Larger Than Block-Size Key - Hash Key First'
data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' +
'c6f636b2d53697a65204b6579202d2048617368204b657920' + 'c6f636b2d53697a65204b6579202d2048617368204b657920' +
'4669727374', 'hex'), '4669727374', 'hex'),
hmac: { hmac: {
@ -167,7 +167,7 @@ var rfc4231 = [
} }
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
@ -176,7 +176,7 @@ var rfc4231 = [
// 'This is a test using a larger than block-size key and a larger ' + // 'This is a test using a larger than block-size key and a larger ' +
// 'than block-size data. The key needs to be hashed before being ' + // 'than block-size data. The key needs to be hashed before being ' +
// 'used by the HMAC algorithm.' // 'used by the HMAC algorithm.'
data: new Buffer('5468697320697320612074657374207573696e672061206c6' + data: Buffer.from('5468697320697320612074657374207573696e672061206c6' +
'172676572207468616e20626c6f636b2d73697a65206b6579' + '172676572207468616e20626c6f636b2d73697a65206b6579' +
'20616e642061206c6172676572207468616e20626c6f636b2' + '20616e642061206c6172676572207468616e20626c6f636b2' +
'd73697a6520646174612e20546865206b6579206e65656473' + 'd73697a6520646174612e20546865206b6579206e65656473' +
@ -216,7 +216,7 @@ for (let i = 0, l = rfc4231.length; i < l; i++) {
// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases)
var rfc2202_md5 = [ var rfc2202_md5 = [
{ {
key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
data: 'Hi There', data: 'Hi There',
hmac: '9294727a3638bb1c13f48ef8158bfc9d' hmac: '9294727a3638bb1c13f48ef8158bfc9d'
}, },
@ -226,28 +226,28 @@ var rfc2202_md5 = [
hmac: '750c783e6ab0b503eaa86e310a5db738' hmac: '750c783e6ab0b503eaa86e310a5db738'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
'hex'), 'hex'),
hmac: '56be34521d144c88dbb8c733f0e8b3f6' hmac: '56be34521d144c88dbb8c733f0e8b3f6'
}, },
{ {
key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
'hex'), 'hex'),
data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
'cdcdcdcdcd', 'cdcdcdcdcd',
'hex'), 'hex'),
hmac: '697eaf0aca3a3aea3a75164746ffaa79' hmac: '697eaf0aca3a3aea3a75164746ffaa79'
}, },
{ {
key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
data: 'Test With Truncation', data: 'Test With Truncation',
hmac: '56461ef2342edc00f9bab995690efd4c' hmac: '56461ef2342edc00f9bab995690efd4c'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaa',
@ -256,7 +256,7 @@ var rfc2202_md5 = [
hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaa',
@ -269,7 +269,7 @@ var rfc2202_md5 = [
]; ];
var rfc2202_sha1 = [ var rfc2202_sha1 = [
{ {
key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
data: 'Hi There', data: 'Hi There',
hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' hmac: 'b617318655057264e28bc0b6fb378c8ef146be00'
}, },
@ -279,29 +279,29 @@ var rfc2202_sha1 = [
hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' +
'ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' +
'dddddddddd', 'dddddddddd',
'hex'), 'hex'),
hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3'
}, },
{ {
key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
'hex'), 'hex'),
data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
'cdcdcdcdcd', 'cdcdcdcdcd',
'hex'), 'hex'),
hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da'
}, },
{ {
key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
data: 'Test With Truncation', data: 'Test With Truncation',
hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaa',
@ -310,7 +310,7 @@ var rfc2202_sha1 = [
hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112'
}, },
{ {
key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaa',
@ -364,7 +364,7 @@ assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
'Test SHA512 as assumed binary'); 'Test SHA512 as assumed binary');
assert.deepEqual(a4, assert.deepEqual(a4,
new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'),
'Test SHA1'); 'Test SHA1');
// Test multiple updates to same hash // Test multiple updates to same hash
@ -497,18 +497,18 @@ function testCipher4(key, iv) {
if (!common.hasFipsCrypto) { if (!common.hasFipsCrypto) {
testCipher1('MySecretKey123'); testCipher1('MySecretKey123');
testCipher1(new Buffer('MySecretKey123')); testCipher1(Buffer.from('MySecretKey123'));
testCipher2('0123456789abcdef'); testCipher2('0123456789abcdef');
testCipher2(new Buffer('0123456789abcdef')); testCipher2(Buffer.from('0123456789abcdef'));
} }
testCipher3('0123456789abcd0123456789', '12345678'); testCipher3('0123456789abcd0123456789', '12345678');
testCipher3('0123456789abcd0123456789', new Buffer('12345678')); testCipher3('0123456789abcd0123456789', Buffer.from('12345678'));
testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); testCipher3(Buffer.from('0123456789abcd0123456789'), '12345678');
testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher3(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher4(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
// update() should only take buffers / strings // update() should only take buffers / strings

4
test/parallel/test-crypto-cipher-decipher.js

@ -67,10 +67,10 @@ function testCipher2(key) {
} }
testCipher1('MySecretKey123'); testCipher1('MySecretKey123');
testCipher1(new Buffer('MySecretKey123')); testCipher1(Buffer.from('MySecretKey123'));
testCipher2('0123456789abcdef'); testCipher2('0123456789abcdef');
testCipher2(new Buffer('0123456789abcdef')); testCipher2(Buffer.from('0123456789abcdef'));
// Base64 padding regression test, see #4837. // Base64 padding regression test, see #4837.
(function() { (function() {

8
test/parallel/test-crypto-cipheriv-decipheriv.js

@ -58,8 +58,8 @@ function testCipher2(key, iv) {
} }
testCipher1('0123456789abcd0123456789', '12345678'); testCipher1('0123456789abcd0123456789', '12345678');
testCipher1('0123456789abcd0123456789', new Buffer('12345678')); testCipher1('0123456789abcd0123456789', Buffer.from('12345678'));
testCipher1(new Buffer('0123456789abcd0123456789'), '12345678'); testCipher1(Buffer.from('0123456789abcd0123456789'), '12345678');
testCipher1(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher1(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
testCipher2(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher2(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));

3
test/parallel/test-crypto-dh-odd-key.js

@ -9,8 +9,7 @@ if (!common.hasCrypto) {
var crypto = require('crypto'); var crypto = require('crypto');
function test() { function test() {
var odd = new Buffer(39); var odd = Buffer.alloc(39, 'A');
odd.fill('A');
var c = crypto.createDiffieHellman(32); var c = crypto.createDiffieHellman(32);
c.setPrivateKey(odd); c.setPrivateKey(odd);

4
test/parallel/test-crypto-dh.js

@ -86,7 +86,7 @@ assert.equal(bob.verifyError, constants.DH_NOT_SUITABLE_GENERATOR);
* The values below (modp2/modp2buf) are for a 1024 bits long prime from * The values below (modp2/modp2buf) are for a 1024 bits long prime from
* RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ * RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */
var modp2 = crypto.createDiffieHellmanGroup('modp2'); var modp2 = crypto.createDiffieHellmanGroup('modp2');
var modp2buf = new Buffer([ var modp2buf = Buffer.from([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f,
0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b,
0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67,
@ -101,7 +101,7 @@ var modp2buf = new Buffer([
0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
]); ]);
var exmodp2 = crypto.createDiffieHellman(modp2buf, new Buffer([2])); var exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2]));
modp2.generateKeys(); modp2.generateKeys();
exmodp2.generateKeys(); exmodp2.generateKeys();
var modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); var modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex');

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save