rustwasm / wasm-bindgen

Facilitating high-level interactions between Wasm modules and JavaScript
https://rustwasm.github.io/docs/wasm-bindgen/
Apache License 2.0
7.86k stars 1.08k forks source link

Request: Implement Hash trait for JsString #2085

Open sergeyt opened 4 years ago

sergeyt commented 4 years ago

Motivation

This allows using JsString value as key in HashMap.

Proposed Solution

It should be straitword, just iterate over chars and write them to hasher.

Alternatives

You can use String::from(value) to convert JsString value to String.

sergeyt commented 4 years ago

Perhaps it is minor thing, but it would be nice to have some day

Pauan commented 4 years ago

Note that iterating over the chars is going to be pretty slow, and unpaired surrogates will need to be handled somehow, so we can't just rely on Rust's char. But maybe we can use u32 instead.

0xd4d commented 4 years ago

The hash code could be calculated in JS, so there'd be only one call to JS instead of one call per char.

RReverser commented 4 years ago

@0xd4d That's not how Hash trait works. It's supposed to work with variety of different hashers, so it expects you to write bytes to the provided Hasher and it would do the rest.

Either using charCodeAt for iterating over u32s as @Pauan suggested, or encoding string into binary, would be the correct solution. Just needs measurements on which one is actually faster.