alchemy_styles/
style_keys.rs1use std::fmt::{Display, Error, Formatter};
8use std::ops::Deref;
9use std::str::FromStr;
10
11#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
17pub struct StyleKey(String);
18
19impl StyleKey {
20 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 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}