From 052ad0bf77fae364868ccbe1653d458a06b18249 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sun, 10 Dec 2023 12:09:43 -0700 Subject: [PATCH] Limb: simplify `Ord` impl Uses the `ConditionallySelectable` impl on `Ordering` to simplify the implementation. --- src/limb/cmp.rs | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/limb/cmp.rs b/src/limb/cmp.rs index bd3fff701..a8d8622bf 100644 --- a/src/limb/cmp.rs +++ b/src/limb/cmp.rs @@ -2,7 +2,9 @@ use crate::{CtChoice, Limb}; use core::cmp::Ordering; -use subtle::{Choice, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess}; +use subtle::{ + Choice, ConditionallySelectable, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess, +}; impl Limb { /// Is this limb an odd number? @@ -62,19 +64,11 @@ impl Eq for Limb {} impl Ord for Limb { fn cmp(&self, other: &Self) -> Ordering { - let mut n = 0i8; - n -= self.ct_lt(other).unwrap_u8() as i8; - n += self.ct_gt(other).unwrap_u8() as i8; - - match n { - -1 => Ordering::Less, - 1 => Ordering::Greater, - _ => { - debug_assert_eq!(n, 0); - debug_assert!(bool::from(self.ct_eq(other))); - Ordering::Equal - } - } + let mut ret = Ordering::Less; + ret.conditional_assign(&Ordering::Equal, self.ct_eq(other)); + ret.conditional_assign(&Ordering::Greater, self.ct_gt(other)); + debug_assert_eq!(ret == Ordering::Less, self.ct_lt(other).into()); + ret } }