From c168d90ead13075b927a8d0737c21b1a7c4fa0ff Mon Sep 17 00:00:00 2001 From: Glenn Smith Date: Wed, 31 Aug 2022 23:01:32 -0400 Subject: [Rust API] Trait for Confidence-mergable types --- rust/src/types.rs | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) (limited to 'rust/src') diff --git a/rust/src/types.rs b/rust/src/types.rs index 0a558228..90f595ed 100644 --- a/rust/src/types.rs +++ b/rust/src/types.rs @@ -47,6 +47,13 @@ pub struct Conf { pub confidence: u8, } +pub trait ConfMergable { + type Result; + /// Merge two confidence types' values depending on whichever has higher confidence + /// In the event of a tie, the LHS (caller's) value is used. + fn merge(self, other: O) -> Self::Result; +} + impl Conf { pub fn new(contents: T, confidence: u8) -> Self { Self { @@ -70,6 +77,76 @@ impl Conf { } } +/// Conf + Conf ==> Conf +/// Returns best value or LHS on tie +impl ConfMergable> for Conf { + type Result = Conf; + fn merge(self, other: Conf) -> Conf { + if other.confidence > self.confidence { + other + } else { + self + } + } +} + +/// Conf + Option> ==> Conf +/// Returns LHS if RHS is None +impl ConfMergable>> for Conf { + type Result = Conf; + fn merge(self, other: Option>) -> Conf { + match other { + Some(c @ Conf { confidence, .. }) if confidence > self.confidence => c, + _ => self, + } + } +} + +/// Option> + Conf ==> Conf +/// Returns RHS if LHS is None +impl ConfMergable> for Option> { + type Result = Conf; + fn merge(self, other: Conf) -> Conf { + match self { + Some(c @ Conf { confidence, .. }) if confidence >= other.confidence => c, + _ => other, + } + } +} + +/// Option> + Option> ==> Option> +/// Returns best non-None value or None +impl ConfMergable>> for Option> { + type Result = Option>; + fn merge(self, other: Option>) -> Option> { + match (self, other) { + ( + Some( + this @ Conf { + confidence: this_confidence, + .. + }, + ), + Some( + other @ Conf { + confidence: other_confidence, + .. + }, + ), + ) => { + if this_confidence >= other_confidence { + Some(this) + } else { + Some(other) + } + } + (None, Some(c)) => Some(c), + (Some(c), None) => Some(c), + (None, None) => None, + } + } +} + impl Debug for Conf { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?} ({} confidence)", self.contents, self.confidence) -- cgit v1.3.1