From 1fe74c64a03009e1ce3671cd4c3109478724acd3 Mon Sep 17 00:00:00 2001 From: Andre Arko Date: Mon, 10 Feb 2014 12:06:39 +0100 Subject: [PATCH] add cmp() to f32 and f64, with tests Sometimes, it becomes necessary to find out if one of your floats is bigger or smaller than another one of your floats. In my case, I had a list of floats I had calculated, and I wanted to sort them biggest to smallest. Using `sort_by()` requires cmp, so I initially wrote my own fcmp, and then realized that was silly and it should just be built in. --- src/libstd/cmp.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/libstd/cmp.rs b/src/libstd/cmp.rs index 1283aba9729b9..7e0145973f2ec 100644 --- a/src/libstd/cmp.rs +++ b/src/libstd/cmp.rs @@ -72,6 +72,9 @@ totaleq_impl!(uint) totaleq_impl!(char) +totaleq_impl!(f32) +totaleq_impl!(f64) + #[deriving(Clone, Eq)] pub enum Ordering { Less = -1, Equal = 0, Greater = 1 } @@ -126,6 +129,9 @@ totalord_impl!(uint) totalord_impl!(char) +totalord_impl!(f32) +totalord_impl!(f64) + /// Compares (a1, b1) against (a2, b2), where the a values are more significant. pub fn cmp2( a1: &A, b1: &B, @@ -216,6 +222,18 @@ mod test { assert!(!2.equals(&17)); } + #[test] + fn test_f32_totaleq() { + assert!(3.14f32.cmp(3.0f32), Less); + assert!(4.12f32.cmp(4.11f32), Greater); + } + + #[test] + fn test_f64_totaleq() { + assert!(3.14f64.cmp(3.0f64), Less); + assert!(4.12f64.cmp(4.11f64), Greater); + } + #[test] fn test_ordering_order() { assert!(Less < Equal);