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

3 4 5
use glib_sys;
use glib::translate::*;
use libc;
6 7
use std::str::FromStr;

8 9
use util::utf8_cstr;

10 11 12 13 14 15 16 17 18 19
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(())
    }
}

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#[no_mangle]
pub extern fn rsvg_attribute_from_name(raw_name: *const libc::c_char,
                                       out_attr: *mut Attribute) -> glib_sys::gboolean {
    let name = unsafe { utf8_cstr(raw_name) };

    match Attribute::from_str(name) {
        Ok(a) => {
            unsafe { *out_attr = a; }
            true.to_glib()
        },

        Err(_) => {
            false.to_glib()
        }
    }
}

37 38
#[cfg(test)]
mod tests {
39
    use std::mem;
40 41 42 43 44 45 46 47 48 49 50
    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(()));
    }
51 52 53 54

    #[test]
    fn c_attribute_from_name() {
        let mut a: Attribute = unsafe { mem::uninitialized() };
55
        let res: bool = from_glib(rsvg_attribute_from_name("width".to_glib_none().0,
56 57 58 59 60 61 62 63
                                                           &mut a as *mut Attribute));
        assert!(res);
        assert_eq!(a, Attribute::Width);
    }

    #[test]
    fn invalid_c_attribute_from_name() {
        let mut a: Attribute = unsafe { mem::uninitialized() };
64
        let res: bool = from_glib(rsvg_attribute_from_name("foobar".to_glib_none().0,
65 66 67
                                                           &mut a as *mut Attribute));
        assert!(!res);
    }
68
}