From a0a37f29f07db29e105450fa080b596f26c38de2 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 16 Jun 2017 12:35:15 -0700 Subject: [PATCH] buffer: support boxed strings and toPrimitive Add support for `Buffer.from(new String('...'))` and `Buffer.from({[Symbol.toPrimitive]() { return '...'; }})` PR-URL: https://github.com/nodejs/node/pull/13725 Reviewed-By: Anna Henningsen Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig --- doc/api/buffer.md | 38 +++++++++++++++++++++ lib/buffer.js | 18 ++++++++-- test/parallel/test-buffer-from.js | 57 +++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-buffer-from.js diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 4488ae2ad9bf8d..3a04ad514b4d4e 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -908,6 +908,44 @@ console.log(buf2.toString()); A `TypeError` will be thrown if `str` is not a string. +### Class Method: Buffer.from(object[, offsetOrEncoding[, length]]) + + +* `object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()` +* `offsetOrEncoding` {number|string} A byte-offset or encoding, depending on + the value returned either by `object.valueOf()` or + `object[Symbol.toPrimitive]()`. +* `length` {number} A length, depending on the value returned either by + `object.valueOf()` or `object[Symbol.toPrimitive]()`. + +For objects whose `valueOf()` function returns a value not strictly equal to +`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`. + +For example: + +```js +const buf = Buffer.from(new String('this is a test')); +// +``` + +For objects that support `Symbol.toPrimitive`, returns +`Buffer.from(object[Symbol.toPrimitive](), offsetOrEncoding, length)`. + +For example: + +```js +class Foo { + [Symbol.toPrimitive]() { + return 'this is a test'; + } +} + +const buf = Buffer.from(new Foo(), 'utf8'); +// +``` + ### Class Method: Buffer.isBuffer(obj)