1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::borrow::Cow;
use std::fmt;

/// A sass name, used to idenify functions, variables, mixins, etc.
///
/// A `-` and a `_` is considered equal in a name, both represented by a `_`.
///
/// # Examples
/// ```
/// # use rsass::sass::Name;
/// assert_eq!(Name::from("foo-bar"), Name::from("foo_bar"));
/// assert_eq!(Name::from_static("foo_bar"), Name::from("foo-bar"));
/// ```
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct Name {
    key: Cow<'static, str>,
}

impl Name {
    /// Key must not contain `-`.
    ///
    /// This function panics in debug mode if the key contains `-`.
    pub fn from_static(key: &'static str) -> Name {
        debug_assert!(!key.contains('-'));
        Name { key: key.into() }
    }

    /// Check if a name is "module.local".
    ///
    /// If so, return the module name and the local name as separate names.
    pub fn split_module(&self) -> Option<(String, Name)> {
        let mut parts = self.key.splitn(2, '.');
        if let (Some(module), Some(local)) = (parts.next(), parts.next()) {
            Some((
                module.to_string(),
                Name {
                    key: local.to_string().into(),
                },
            ))
        } else {
            None
        }
    }
}

impl fmt::Display for Name {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        self.key.replace('_', "-").fmt(out)
    }
}

impl AsRef<str> for Name {
    fn as_ref(&self) -> &str {
        self.key.as_ref()
    }
}

impl From<String> for Name {
    fn from(key: String) -> Name {
        if key.contains('-') {
            Name {
                key: key.replace('-', "_").into(),
            }
        } else {
            Name { key: key.into() }
        }
    }
}

impl From<&str> for Name {
    fn from(key: &str) -> Name {
        Name {
            key: key.replace('-', "_").into(),
        }
    }
}
impl From<&String> for Name {
    fn from(key: &String) -> Name {
        let key: &str = key.as_ref();
        key.into()
    }
}

#[test]
fn test() {
    assert_eq!(Name::from_static("foo_bar"), "foo_bar".into());
    assert_eq!(Name::from_static("foo_bar"), "foo-bar".into());
    assert_eq!(Name::from_static("foo_bar"), "foo_bar".to_string().into());
    assert_eq!(Name::from_static("foo_bar"), "foo-bar".to_string().into());
}