Skip to content

num_rational::Ratio's Hash is incompatible with Eq. #310

@kennytm

Description

@kennytm

As of 0.1.38, num_rational::Ratio implements PartialEq and Eq by the numeric value, while Hash is derived. This violates the rule of Eq + Hash which is a == b ⇒ hash(a) == hash(b) when non-reduced ratio is involved:

let a = Rational::new_raw(4, 2);
let b = Rational::new_raw(6, 3);
assert_eq!(a, b); // ok.

let mut h = HashSet::new();
h.insert(a);
h.insert(b);
assert_eq!(h.len(), 1); // likely panic, 2 ≠ 1

The hash should be computed using the reduced value. This unfortunately means the GCD will need to be calculated every time we need the hash.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions