diff options
| author | Glenn Smith <glenn@vector35.com> | 2022-08-31 23:01:32 -0400 |
|---|---|---|
| committer | Glenn Smith <glenn@vector35.com> | 2022-09-29 21:02:23 -0400 |
| commit | c168d90ead13075b927a8d0737c21b1a7c4fa0ff (patch) | |
| tree | ed5fdb4a9810dc09b33f6f0b5122fdf154ac75e5 /rust/src | |
| parent | 8cbdc0e05adefd58e6939f7bb70d6f031277e4f6 (diff) | |
[Rust API] Trait for Confidence-mergable types
Diffstat (limited to 'rust/src')
| -rw-r--r-- | rust/src/types.rs | 77 |
1 files changed, 77 insertions, 0 deletions
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<T> { pub confidence: u8, } +pub trait ConfMergable<T, O> { + 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<T> Conf<T> { pub fn new(contents: T, confidence: u8) -> Self { Self { @@ -70,6 +77,76 @@ impl<T> Conf<T> { } } +/// Conf<T> + Conf<T> ==> Conf<T> +/// Returns best value or LHS on tie +impl<T> ConfMergable<T, Conf<T>> for Conf<T> { + type Result = Conf<T>; + fn merge(self, other: Conf<T>) -> Conf<T> { + if other.confidence > self.confidence { + other + } else { + self + } + } +} + +/// Conf<T> + Option<Conf<T>> ==> Conf<T> +/// Returns LHS if RHS is None +impl<T> ConfMergable<T, Option<Conf<T>>> for Conf<T> { + type Result = Conf<T>; + fn merge(self, other: Option<Conf<T>>) -> Conf<T> { + match other { + Some(c @ Conf { confidence, .. }) if confidence > self.confidence => c, + _ => self, + } + } +} + +/// Option<Conf<T>> + Conf<T> ==> Conf<T> +/// Returns RHS if LHS is None +impl<T> ConfMergable<T, Conf<T>> for Option<Conf<T>> { + type Result = Conf<T>; + fn merge(self, other: Conf<T>) -> Conf<T> { + match self { + Some(c @ Conf { confidence, .. }) if confidence >= other.confidence => c, + _ => other, + } + } +} + +/// Option<Conf<T>> + Option<Conf<T>> ==> Option<Conf<T>> +/// Returns best non-None value or None +impl<T> ConfMergable<T, Option<Conf<T>>> for Option<Conf<T>> { + type Result = Option<Conf<T>>; + fn merge(self, other: Option<Conf<T>>) -> Option<Conf<T>> { + 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<T: Debug> Debug for Conf<T> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?} ({} confidence)", self.contents, self.confidence) |
