Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

hashmap on Buffer objects appears to be wrong, why

There are two different Buffer objects (different values) in a JavaScript, but in JavaScript object, they are treated as being equal. Any idea why? How to force them to be different keys for a JavaScript? Thanks

my node.js version is 10.15.1 on Ubuntu 18.04.

var buf1 = Buffer.from([
    10,
    33,
    45,
    77,
    10,
    33,
    46,
    166,
    140,
    190,
    5,
    241
  ]);
var buf2 = new Buffer.from([
    10,
    33,
    45,
    77,
    10,
    33,
    46,
    168,
    215,
    216,
    5,
    241
]);
let a = {};
a[buf2] = "jon";
console.log(a[buf1]);  //output  jon

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

a[buf2] is equivalent to a[buf2.toString()], which is equivalent to a[buf2.toString('utf-8')], which is the cause of your problem: your buffers don’t hold valid UTF-8 data, so when converting to an UTF-8 string, invalid code points are replaced by the Unicode replacement character, U+FFFD (encoded as 0xEF 0xBF 0xBD in UTF-8).

To show this, you can run the following code:

console.log('buf1', Buffer.from(buf1.toString()).toString('hex'));
console.log('buf2', Buffer.from(buf2.toString()).toString('hex'));

The result is the hexadecimal representation of each buffer as it’s used as a property "name" (replacement character highlighted):

buf1 0a212d4d0a212eefbfbdefbfbdefbfbd05efbfbd
                   ^^^^^^^^^^^^^^^^^^  ^^^^^^
buf2 0a212d4d0a212eefbfbdefbfbdefbfbd05efbfbd

As you can see, they are equivalent.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading