From 32e3658b10ab70e1300ac1aa8b413765b411acbe Mon Sep 17 00:00:00 2001 From: pml68 Date: Sat, 1 Mar 2025 02:29:38 +0100 Subject: feat: impl `Value` for `Pixels` and `Alignment` --- src/values/alignment.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/values/alignment.rs (limited to 'src/values/alignment.rs') diff --git a/src/values/alignment.rs b/src/values/alignment.rs new file mode 100644 index 0000000..7e9fcab --- /dev/null +++ b/src/values/alignment.rs @@ -0,0 +1,65 @@ +use iced::Alignment; + +use super::Value; + +#[derive(Debug, thiserror::Error, Clone, PartialEq)] +pub enum ParseAlignmentError { + #[error("cannot parse rotation from empty string")] + Empty, + #[error("invalid variant")] + InvalidVariant, +} + +impl Value for Alignment { + type Err = ParseAlignmentError; + + fn from_str(s: &str) -> Result { + let s = s.trim(); + + if s.is_empty() { + return Err(ParseAlignmentError::Empty); + } + + match s { + "start" => Ok(Self::Start), + "center" => Ok(Self::Center), + "end" => Ok(Self::End), + _ => Err(ParseAlignmentError::InvalidVariant), + } + } + + fn to_string(&self) -> String { + match self { + Self::Start => String::from("start"), + Self::Center => String::from("center"), + Self::End => String::from("end"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn can_parse_with_spaces() { + assert_eq!(Alignment::from_str(" start"), Ok(Alignment::Start)); + + assert_eq!(Alignment::from_str(" center "), Ok(Alignment::Center)); + + assert_eq!(Alignment::from_str("end "), Ok(Alignment::End)) + } + + #[test] + fn cant_parse_invalid_variant() { + assert_eq!( + Alignment::from_str("middle"), + Err(ParseAlignmentError::InvalidVariant) + ) + } + + #[test] + fn cant_parse_empty_string() { + assert_eq!(Alignment::from_str(" "), Err(ParseAlignmentError::Empty)) + } +} -- cgit v1.2.3