-
Notifications
You must be signed in to change notification settings - Fork 28.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
buffer: support boxed strings and toPrimitive
Add support for `Buffer.from(new String('...'))` and `Buffer.from({[Symbol.toPrimitive]() { return '...'; }})` PR-URL: #13725 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Refael Ackermann <refack@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
- Loading branch information
Showing
3 changed files
with
111 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
'use strict'; | ||
|
||
require('../common'); | ||
const { deepStrictEqual, throws } = require('assert'); | ||
const { Buffer } = require('buffer'); | ||
const { runInNewContext } = require('vm'); | ||
|
||
const checkString = 'test'; | ||
|
||
const check = Buffer.from(checkString); | ||
|
||
class MyString extends String { | ||
constructor() { | ||
super(checkString); | ||
} | ||
} | ||
|
||
class MyPrimitive { | ||
[Symbol.toPrimitive]() { | ||
return checkString; | ||
} | ||
} | ||
|
||
class MyBadPrimitive { | ||
[Symbol.toPrimitive]() { | ||
return 1; | ||
} | ||
} | ||
|
||
deepStrictEqual(Buffer.from(new String(checkString)), check); | ||
deepStrictEqual(Buffer.from(new MyString()), check); | ||
deepStrictEqual(Buffer.from(new MyPrimitive()), check); | ||
deepStrictEqual(Buffer.from( | ||
runInNewContext('new String(checkString)', {checkString})), | ||
check); | ||
|
||
const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' + | ||
'ArrayBuffer, Array, or array-like object\\.$'); | ||
|
||
[ | ||
{}, | ||
new Boolean(true), | ||
{ valueOf() { return null; } }, | ||
{ valueOf() { return undefined; } }, | ||
{ valueOf: null }, | ||
Object.create(null) | ||
].forEach((input) => { | ||
throws(() => Buffer.from(input), err); | ||
}); | ||
|
||
[ | ||
new Number(true), | ||
new MyBadPrimitive() | ||
].forEach((input) => { | ||
throws(() => Buffer.from(input), | ||
/^TypeError: "value" argument must not be a number$/); | ||
}); |