alchemy_styles/
style_keys.rs

1//! A valid CSS class.
2//!
3//! A CSS class is a non-empty string that starts with an alphanumeric character
4//! and is followed by any number of alphanumeric characters and the
5//! `_`, `-` and `.` characters.
6
7use std::fmt::{Display, Error, Formatter};
8use std::ops::Deref;
9use std::str::FromStr;
10
11/// A valid CSS class.
12///
13/// A CSS class is a non-empty string that starts with an alphanumeric character
14/// and is followed by any number of alphanumeric characters and the
15/// `_`, `-` and `.` characters.
16#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
17pub struct StyleKey(String);
18
19impl StyleKey {
20    /// Construct a new styles list from a string.
21    ///
22    /// Returns `Err` if the provided string is invalid.
23    pub fn try_new<S: Into<String>>(id: S) -> Result<Self, &'static str> {
24        let id = id.into();
25        {
26            let mut chars = id.chars();
27            match chars.next() {
28                None => return Err("style keys cannot be empty"),
29                Some(c) if !c.is_alphabetic() => {
30                    return Err("style keys must start with an alphabetic character")
31                }
32                _ => (),
33            }
34            for c in chars {
35                if !c.is_alphanumeric() && c != '-' {
36                    return Err(
37                        "style keys can only contain alphanumerics (dash included)",
38                    );
39                }
40            }
41        }
42        Ok(StyleKey(id))
43    }
44
45    /// Construct a new class name from a string.
46    ///
47    /// Panics if the provided string is invalid.
48    pub fn new<S: Into<String>>(id: S) -> Self {
49        let id = id.into();
50        Self::try_new(id.clone()).unwrap_or_else(|err| {
51            panic!(
52                "alchemy::dom::types::StyleKey: {:?} is not a valid class name: {}",
53                id, err
54            )
55        })
56    }
57}
58
59impl FromStr for StyleKey {
60    type Err = &'static str;
61    fn from_str(s: &str) -> Result<Self, Self::Err> {
62        StyleKey::try_new(s)
63    }
64}
65
66impl<'a> From<&'a str> for StyleKey {
67    fn from(str: &'a str) -> Self {
68        StyleKey::from_str(str).unwrap()
69    }
70}
71
72impl Display for StyleKey {
73    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
74        Display::fmt(&self.0, f)
75    }
76}
77
78impl Deref for StyleKey {
79    type Target = String;
80    fn deref(&self) -> &Self::Target {
81        &self.0
82    }
83}