achanda / ipnetwork

A library to work with CIDRs in rust
Apache License 2.0
121 stars 38 forks source link

netsize: Hash implementation to match PartialEq #186

Closed Alextopher closed 5 months ago

Alextopher commented 5 months ago

Hash and PartialEq implementations on NetworkSize are mutually incompatible and don't follow the std::hash::Hash constraints. This will cause issues if you use NetworkSize in a HashMap or HashSet.

It is required that the keys implement the Eq and Hash traits, although this can frequently be achieved by using #[derive(PartialEq, Eq, Hash)]. If you implement these yourself, it is important that the following property holds:

k1 == k2 -> hash(k1) == hash(k2)

In other words, if two keys are equal, their hashes must be equal. Violating this property is a logic error.

Here is a playground link demonstrating the issue. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d030b1654e0abd2515c16ffe83fcd9a0

This PR fixes this issue by writing a custom implementation of Hash which only use the u128 logical value of the network size, same as PartialEq.

Alextopher commented 5 months ago

This playground link shows off the expected behavior https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=32d06a7fb1e8473fea5e3c460add8944

Alextopher commented 5 months ago

Further changes here:

Alextopher commented 5 months ago

This fixes a bug introduced in #175