From 1e21c08acd6621cae2b54ed1bac85ead3884cf44 Mon Sep 17 00:00:00 2001 From: therealyingtong Date: Wed, 7 Oct 2020 21:54:00 +0800 Subject: [PATCH] Implement Ord and PartialOrd for Field --- src/arithmetic/fields.rs | 2 ++ src/arithmetic/fields/fp.rs | 22 ++++++++++++++++++++++ src/arithmetic/fields/fq.rs | 22 ++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/src/arithmetic/fields.rs b/src/arithmetic/fields.rs index 45b9f7b..67c3043 100644 --- a/src/arithmetic/fields.rs +++ b/src/arithmetic/fields.rs @@ -36,6 +36,8 @@ pub trait Field: + for<'a> SubAssign<&'a Self> + PartialEq + Eq + + PartialOrd + + Ord + ConditionallySelectable + ConstantTimeEq + Group diff --git a/src/arithmetic/fields/fp.rs b/src/arithmetic/fields/fp.rs index f85b75e..fd02695 100644 --- a/src/arithmetic/fields/fp.rs +++ b/src/arithmetic/fields/fp.rs @@ -62,6 +62,28 @@ impl PartialEq for Fp { } } +impl std::cmp::Ord for Fp { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + let left = self.to_bytes(); + let right = other.to_bytes(); + for (left_byte, right_byte) in left.iter().zip(right.iter()).rev() { + let tmp = left_byte.cmp(right_byte); + if let std::cmp::Ordering::Equal = tmp { + continue; + } else { + return tmp; + } + } + std::cmp::Ordering::Equal + } +} + +impl std::cmp::PartialOrd for Fp { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + impl ConditionallySelectable for Fp { fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self { Fp([ diff --git a/src/arithmetic/fields/fq.rs b/src/arithmetic/fields/fq.rs index 1005263..0f99629 100644 --- a/src/arithmetic/fields/fq.rs +++ b/src/arithmetic/fields/fq.rs @@ -62,6 +62,28 @@ impl PartialEq for Fq { } } +impl std::cmp::Ord for Fq { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + let left = self.to_bytes(); + let right = other.to_bytes(); + for (left_byte, right_byte) in left.iter().zip(right.iter()).rev() { + let tmp = left_byte.cmp(right_byte); + if let std::cmp::Ordering::Equal = tmp { + continue; + } else { + return tmp; + } + } + std::cmp::Ordering::Equal + } +} + +impl std::cmp::PartialOrd for Fq { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + impl ConditionallySelectable for Fq { fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self { Fq([