-
Notifications
You must be signed in to change notification settings - Fork 29.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Converting String-object to Buffer fails to copy data #13652
Comments
It's because there is no special treatment for string objects, they are interpreted as array-like objects with their elements coerced to numeric values. That is, these are all equal: Buffer.from(new String('x'));
Buffer.from({ length: 1, [0]: 'x' });
Buffer.from({ length: 1, [0]: +'x' }); // +'x' -> Nan -> 0 Node has no special treatment for string objects elsewhere either so it's a bit of an open question if we should do it here. |
Ah... eww... okay. I had hoped to use a String subclass to mark certain strings as having some particular semantic value, but somewhere down the road they get converted to buffer in third party code.... oh well, it briefly seemed like a good idea. With the introduction of things like String subclasses, Symbol.toPrimitive, etc it would definitely have been nice if they had also included an authoritive way code can figure out how it's supposed to treat objects... "are you trying to be an array? a string? a number maybe?" |
@mvduin just to be clear - what would you expect the behavior to be in this case noting:
? |
That's not what I meant, but never mind - you can ignore that bit of my comment. |
@mvduin ... the easiest thing to do would be just: Buffer.from(new String('test').valueOf());
// or
Buffer.from(new String('test').toString()); That would allow you to do the String subclassing. That said, I can see a case being made to allow |
I think a reasonable case can be made that the current behavior is confusing and possibly insecure in some circumstances. Consider how a string of digits is parsed differently based on whether the value is a primitive string or a string object:
Vs.
You wouldn't write such code directly but if you pass in a variable |
Exactly, the issue didn't happen directly in my code but in third party code that got my non-primitive strings somewhere down the road and transmitted them over a socket |
@mvduin I think in this case there is a somewhat related symbol, it's I think it's an open question how |
Does this still need to stay open? /cc @jasnell |
This seems to be resolved in #13725, but I may be wrong, in which case, please feel free to reopen this. |
Looks good to me, thanks! |
Creating a buffer from a String object results in a zero-filled buffer (of length equal to the string length in UTF-16 code-units):
The text was updated successfully, but these errors were encountered: