Skip to content

Add hashing support compatible with std::hash #11

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

Merged
merged 4 commits into from
Aug 14, 2025

Conversation

brodeuralexis
Copy link
Contributor

This will allow fine::Atoms and fine::Terms to be used as std::map, and std::unordered_map keys if merged with #10.


template <> struct hash<::fine::Atom> {
size_t operator()(const ::fine::Atom &atom) noexcept {
return std::hash<std::string_view>{}(atom.to_string());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To use *atom.term instead would require a rework of fine::Atom.
If receiving the atom from a NIF parameter, atom.term is std::nullopt. The only time when this is not the case is when atoms are globals and initialized during the load NIF callback.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think hashing the string is good!

Copy link
Member

@jonatanklosko jonatanklosko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! There are a few conflicts after #10. Let's also remove the _test suffix here too :)

This is related to elixir-nx#10, and will allow `fine::Atom`s and `fine::Term`s
to be used as `std::map`, and `std::unordered_map` keys.
PHASH2 is guaranteed to be stable across ERTS instance boundaries, hence
making this hashing algorihtm more stable.

This change is expected to reduce the friction for users, as terms will
always hash equal, no matter the ERTS version and instance.
Now, only `std::hash` is supported to hash `fine::Term` and `fine::Atom`
data structures.

Due to the way `fine::Atom` is implemented, we cannot delegate to
`enif_hash` to hash an atom, but must instead hash the atom's string
representation.
Copy link
Member

@jonatanklosko jonatanklosko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@jonatanklosko jonatanklosko merged commit a69298e into elixir-nx:main Aug 14, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants