From b6202b646a0d5ecced301d9bac8bfcaf977d7ee4 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 15 Dec 2022 22:51:55 +0100 Subject: Reflection for castables --- src/geom/mod.rs | 2 ++ src/geom/smart.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/geom/stroke.rs | 1 - 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 src/geom/smart.rs (limited to 'src/geom') diff --git a/src/geom/mod.rs b/src/geom/mod.rs index 3c7c2fc9..6161774b 100644 --- a/src/geom/mod.rs +++ b/src/geom/mod.rs @@ -21,6 +21,7 @@ mod rounded; mod scalar; mod sides; mod size; +mod smart; mod stroke; mod transform; @@ -43,6 +44,7 @@ pub use self::rounded::*; pub use self::scalar::*; pub use self::sides::*; pub use self::size::*; +pub use self::smart::*; pub use self::stroke::*; pub use self::transform::*; diff --git a/src/geom/smart.rs b/src/geom/smart.rs new file mode 100644 index 00000000..d20bcdfe --- /dev/null +++ b/src/geom/smart.rs @@ -0,0 +1,64 @@ +use super::*; + +/// A value that can be automatically determined. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub enum Smart { + /// The value should be determined smartly based on the circumstances. + Auto, + /// A specific value. + Custom(T), +} + +impl Smart { + /// Map the contained custom value with `f`. + pub fn map(self, f: F) -> Smart + where + F: FnOnce(T) -> U, + { + match self { + Self::Auto => Smart::Auto, + Self::Custom(x) => Smart::Custom(f(x)), + } + } + + /// Keeps `self` if it contains a custom value, otherwise returns `other`. + pub fn or(self, other: Smart) -> Self { + match self { + Self::Custom(x) => Self::Custom(x), + Self::Auto => other, + } + } + + /// Returns the contained custom value or a provided default value. + pub fn unwrap_or(self, default: T) -> T { + match self { + Self::Auto => default, + Self::Custom(x) => x, + } + } + + /// Returns the contained custom value or computes a default value. + pub fn unwrap_or_else(self, f: F) -> T + where + F: FnOnce() -> T, + { + match self { + Self::Auto => f(), + Self::Custom(x) => x, + } + } + + /// Returns the contained custom value or the default value. + pub fn unwrap_or_default(self) -> T + where + T: Default, + { + self.unwrap_or_else(T::default) + } +} + +impl Default for Smart { + fn default() -> Self { + Self::Auto + } +} diff --git a/src/geom/stroke.rs b/src/geom/stroke.rs index eae43c24..86191d33 100644 --- a/src/geom/stroke.rs +++ b/src/geom/stroke.rs @@ -1,5 +1,4 @@ use super::*; -use crate::model::Smart; /// A stroke of a geometric shape. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] -- cgit v1.2.3