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
use image::Luma;
use qrcode::QrCode;
use std::collections::hash_map::DefaultHasher;
use std::env;
use std::hash::{Hash, Hasher};

pub struct ImageName {
    pub image_name: String,
}

impl Hash for ImageName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.image_name.hash(state);
    }
}

pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
    let mut s = DefaultHasher::new();
    t.hash(&mut s);
    s.finish()
}

pub fn get_current_path() -> Result<String, Box<dyn std::error::Error>> {
    let path = env::current_dir()?;
    Ok(path.display().to_string())
}

pub fn generate(content: String, name: String) -> Result<(), Box<dyn std::error::Error>> {
    let code = QrCode::new(content).unwrap();
    let image = code.render::<Luma<u8>>().build();

    let current_path: String = get_current_path().unwrap();
    let image_name = ImageName { image_name: name };
    let mut original_image_name = image_name.image_name;
    let image_name_to_hash = calculate_hash(&mut original_image_name).to_string();
    let image_extension = ".png".to_string();
    let image_path: String = format!(
        "{}/{}-{}.{}",
        current_path, original_image_name, image_name_to_hash, image_extension
    );

    image.save(image_path).unwrap();

    Ok(())
}

#[cfg(test)]
mod tests {
    use self::calculate_hash;
    use self::generate;
    use super::*;

    #[test]
    fn test_generate() {
        let content = "https://example.com/path".to_string();
        let name = "name_of_image".to_string();

        assert!(generate(content, name).unwrap() == ())
    }

    #[test]
    fn test_calculate_hash() {
        let image1 = ImageName {
            image_name: "image1".to_string(),
        };

        let image2 = ImageName {
            image_name: "image1".to_string(),
        };

        assert!(calculate_hash(&image1) == calculate_hash(&image2))
    }
}