captcha/fonts/
mod.rs

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
use base64::decode;
use serde_json;
use std::collections::HashMap;

pub trait Font {
    fn png_as_base64(&self, letter: char) -> Option<&String>;

    fn chars(&self) -> Vec<char>;

    /// Returns None if letter does not exist or if letter could not decoded.
    fn png(&self, letter: char) -> Option<Vec<u8>> {
        match self.png_as_base64(letter) {
            None => None,
            Some(s) => match decode(s) {
                Err(_) => None,
                Ok(v) => Some(v),
            },
        }
    }
}

pub struct Default {
    data: HashMap<char, String>,
}

impl Default {
    pub fn new() -> Default {
        let json = include_str!("font_default.json").to_string();

        Default {
            data: serde_json::from_str(&json).expect("invalid json"),
        }
    }
}

impl Font for Default {
    fn png_as_base64(&self, letter: char) -> Option<&String> {
        self.data.get(&letter)
    }

    fn chars(&self) -> Vec<char> {
        self.data.keys().cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use fonts::{Default, Font};
    use images::Image;

    #[test]
    fn fonts_default() {
        let f = Default::new();

        assert_eq!(f.chars().len(), 57);
        assert!(f.png_as_base64('a').is_some());
        assert!(f.png('a').is_some());
        for i in f.chars() {
            assert!(Image::from_png(f.png(i).unwrap()).is_some());
        }
    }
}