eagre_asn1/types/
strings.rs

1use der::{self, DER};
2use std::io::{self, Read, Write};
3
4// Macro for lazy people like me
5macro_rules! string_type {
6    ($name:ident) => {
7        /// Asn1 String Type
8        ///
9        /// Currently restricted character sets are not enforced, so it is
10        /// the callers job to check wether string contents are legal for
11        /// the specific string type
12        #[derive(Debug)]
13        pub struct $name(String);
14
15        impl From<String> for $name {
16            fn from(s: String) -> $name {
17                $name(s)
18            }
19        }
20
21        impl From<$name> for String {
22            fn from(s: $name) -> String {
23                s.0
24            }
25        }
26
27        impl DER for $name {
28            fn der_universal_tag() -> der::UniversalTag {
29                der::UniversalTag::$name
30            }
31
32            fn der_content() -> der::ContentType {
33                der::ContentType::Primitive
34            }
35
36            fn der_encode_content(&self, w: &mut Write) -> io::Result<()> {
37                try!(w.write(self.0.as_bytes()));
38                Ok(())
39            }
40
41            fn der_decode_content(r: &mut Read, length: usize) -> io::Result<$name> {
42                let mut encoded = r.take(length as u64);
43                let mut buffer = String::new();
44                try!(encoded.read_to_string(&mut buffer));
45                Ok($name(buffer))
46            }
47        }
48    }
49}
50
51string_type!(NumericString);
52string_type!(PrintableString);
53string_type!(T61String);
54string_type!(VideotexString);
55string_type!(IA5String);
56string_type!(GraphicString);
57string_type!(VisibleString);
58string_type!(GeneralString);
59string_type!(UniversalString);
60string_type!(CharacterString);
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn sample() {
68        use der::DER;
69        let bytes = IA5String::from("FooBar123".to_string()).der_bytes().unwrap();
70        assert_eq!("FooBar123",
71                   &String::from(IA5String::der_from_bytes(bytes).unwrap()));
72    }
73}