Skip to content

Commit 8138c35

Browse files
committed
num: implement Hash for Complex and Ratio
1 parent f6a7ab4 commit 8138c35

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/libnum/complex.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
//! Complex numbers.
1313
1414
use std::fmt;
15-
use std::num::{Zero,One,ToStrRadix};
15+
use std::num::{Zero, One, ToStrRadix};
1616

1717
// FIXME #1284: handle complex NaN & infinity etc. This
1818
// probably doesn't map to C's _Complex correctly.
1919

2020
/// A complex number in Cartesian form.
21-
#[deriving(PartialEq,Clone)]
21+
#[deriving(PartialEq, Clone, Hash)]
2222
pub struct Complex<T> {
2323
/// Real portion of the complex number
2424
pub re: T,
@@ -193,7 +193,8 @@ mod test {
193193
#![allow(non_uppercase_statics)]
194194

195195
use super::{Complex64, Complex};
196-
use std::num::{Zero,One,Float};
196+
use std::num::{Zero, One, Float};
197+
use std::hash::hash;
197198

198199
pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
199200
pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
@@ -367,4 +368,14 @@ mod test {
367368
test(-_neg1_1i, "1-1i".to_string());
368369
test(_05_05i, "0.5+0.5i".to_string());
369370
}
371+
372+
#[test]
373+
fn test_hash() {
374+
let a = Complex::new(0i32, 0i32);
375+
let b = Complex::new(1i32, 0i32);
376+
let c = Complex::new(0i32, 1i32);
377+
assert!(hash(&a) != hash(&b));
378+
assert!(hash(&b) != hash(&c));
379+
assert!(hash(&c) != hash(&a));
380+
}
370381
}

src/libnum/rational.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use std::num::{Zero, One, ToStrRadix, FromStrRadix};
2121
use bigint::{BigInt, BigUint, Sign, Plus, Minus};
2222

2323
/// Represents the ratio between 2 numbers.
24-
#[deriving(Clone)]
24+
#[deriving(Clone, Hash)]
2525
#[allow(missing_doc)]
2626
pub struct Ratio<T> {
2727
numer: T,
@@ -381,6 +381,7 @@ mod test {
381381
use super::{Ratio, Rational, BigRational};
382382
use std::num::{Zero, One, FromStrRadix, FromPrimitive, ToStrRadix};
383383
use std::from_str::FromStr;
384+
use std::hash::hash;
384385
use std::num;
385386

386387
pub static _0 : Rational = Ratio { numer: 0, denom: 1};
@@ -728,4 +729,10 @@ mod test {
728729
assert!(! _neg1_2.is_positive());
729730
assert!(! _1_2.is_negative());
730731
}
732+
733+
#[test]
734+
fn test_hash() {
735+
assert!(hash(&_0) != hash(&_1));
736+
assert!(hash(&_0) != hash(&_3_2));
737+
}
731738
}

0 commit comments

Comments
 (0)