attributes.rs 1.33 KB
Newer Older
1 2
extern crate phf;

3
use std::fmt;
4 5 6 7 8 9 10 11 12 13 14 15
use std::str::FromStr;

include!(concat!(env!("OUT_DIR"), "/attributes-codegen.rs"));

impl FromStr for Attribute {
    type Err = ();

    fn from_str(s: &str) -> Result<Attribute, ()> {
        ATTRIBUTES.get(s).cloned().ok_or(())
    }
}

16
impl fmt::Display for Attribute {
17 18 19 20
    // This is horribly inefficient, but for now I'm too lazy to have a
    // compile-time bijective mapping from attributes to names.  Hopefully
    // this function is only called when *printing* errors, which, uh,
    // should not be done too often.
21
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22 23
        for (k, v) in ATTRIBUTES.entries() {
            if *v == *self {
24
                return write!(f, "{}", k);
25 26 27 28 29 30 31
            }
        }

        unreachable!();
    }
}

32 33 34 35 36 37 38 39 40 41 42 43 44
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_attributes() {
        assert_eq!(Attribute::from_str("width"), Ok(Attribute::Width));
    }

    #[test]
    fn unknown_attribute_yields_error() {
        assert_eq!(Attribute::from_str("foobar"), Err(()));
    }
45

46 47
    #[test]
    fn converts_attributes_back_to_strings() {
48 49 50
        assert_eq!(Attribute::ClipPath.to_string(), "clip-path");
        assert_eq!(Attribute::KernelUnitLength.to_string(), "kernelUnitLength");
        assert_eq!(Attribute::Offset.to_string(), "offset");
51
    }
52
}