From f251c7cce50df75195b8c21858e44d4ae8c0ebc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Volf?= <66163112+matous-volf@users.noreply.github.com> Date: Mon, 9 Sep 2024 18:48:10 +0200 Subject: [PATCH] feat: create a utility struct for reversing `Option` ordering --- src/main.rs | 1 + src/utils/mod.rs | 1 + src/utils/reverse_ord_option.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 src/utils/mod.rs create mode 100644 src/utils/reverse_ord_option.rs diff --git a/src/main.rs b/src/main.rs index a7a75b6..31ce965 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ mod route; mod schema; mod server; mod query; +mod utils; use components::app::App; use dioxus::prelude::*; diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..84f597f --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1 @@ +pub(crate) mod reverse_ord_option; diff --git a/src/utils/reverse_ord_option.rs b/src/utils/reverse_ord_option.rs new file mode 100644 index 0000000..fa5f9f3 --- /dev/null +++ b/src/utils/reverse_ord_option.rs @@ -0,0 +1,31 @@ +use std::cmp::Ordering; + +/* The default ordering of `Option`s is `None` being less than `Some`. The purpose of this struct is + to reverse that. */ +#[derive(PartialEq)] +pub(crate) struct ReverseOrdOption<'a, T>(&'a Option); + +impl<'a, T: Ord> Eq for ReverseOrdOption<'a, T> {} + +impl<'a, T: Ord> PartialOrd for ReverseOrdOption<'a, T> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl<'a, T: Ord> Ord for ReverseOrdOption<'a, T> { + fn cmp(&self, other: &Self) -> Ordering { + match (self.0.as_ref(), other.0.as_ref()) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(self_time), Some(other_time)) => self_time.cmp(other_time) + } + } +} + +impl<'a, T> From<&'a Option> for ReverseOrdOption<'a, T> { + fn from(value: &'a Option) -> Self { + ReverseOrdOption(value) + } +}