From 5d573231f506797dad6318c90f3dbfc8a1d2133f Mon Sep 17 00:00:00 2001 From: Allan <6740989+allan2@users.noreply.github.com> Date: Mon, 16 Sep 2024 15:51:00 -0400 Subject: [PATCH] Add `PartialEq` and `PartialOrd` for `Score` This allows for comparisons between `Score` and `u8`. The reverse implementations are also added. --- src/scoring.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/scoring.rs b/src/scoring.rs index c11c58d..c6f5b6b 100644 --- a/src/scoring.rs +++ b/src/scoring.rs @@ -48,6 +48,30 @@ impl Display for Score { } } +impl PartialEq for Score { + fn eq(&self, other: &u8) -> bool { + *self as u8 == *other + } +} + +impl PartialEq for u8 { + fn eq(&self, other: &Score) -> bool { + *self == *other as u8 + } +} + +impl PartialOrd for Score { + fn partial_cmp(&self, other: &u8) -> Option { + (*self as u8).partial_cmp(other) + } +} + +impl PartialOrd for u8 { + fn partial_cmp(&self, other: &Score) -> Option { + self.partial_cmp(&(*other as u8)) + } +} + #[derive(Debug, Clone)] pub struct GuessCalculation { /// Estimated guesses needed to crack the password @@ -1162,6 +1186,39 @@ mod tests { } } + #[test] + fn test_score_partial_eq_u8() { + assert_eq!(scoring::Score::Zero, 0); + assert_eq!(scoring::Score::One, 1); + assert_eq!(scoring::Score::Two, 2); + assert_eq!(scoring::Score::Three, 3); + assert_eq!(scoring::Score::Four, 4); + + assert_eq!(0, scoring::Score::Zero); + assert_eq!(1, scoring::Score::One); + assert_eq!(2, scoring::Score::Two); + assert_eq!(3, scoring::Score::Three); + assert_eq!(4, scoring::Score::Four); + } + + #[test] + fn test_score_partial_ord_u8() { + assert!(scoring::Score::Zero < 1); + assert!(scoring::Score::One > 0); + assert!(scoring::Score::Two >= 1); + assert!(scoring::Score::Three <= 4); + + assert!(0 < scoring::Score::One); + assert!(1 > scoring::Score::Zero); + assert!(1 <= scoring::Score::Two); + assert!(4 >= scoring::Score::Three); + + assert!(!(scoring::Score::Zero < 0)); + assert!(!(scoring::Score::Four > 4)); + assert!(!(0 > scoring::Score::Zero)); + assert!(!(4 < scoring::Score::Four)); + } + #[cfg(feature = "ser")] #[test] fn serde_score() {