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
//! Defines helper functions which can be used to retrieve translations

use crate::store::{Store, Unit};
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

/// Translation helper
pub struct T {
    store: Store,
}

impl T {
    /// Initializes a repository for the specified translation format.
    pub fn load(path: &PathBuf) -> Self {
        let mut file = File::open(path).expect("Failed to open the file");

        let mut buffer: Vec<u8> = Default::default();
        file.read_to_end(&mut buffer).expect("failed to read file");

        let mut store: Store = Store::new();
        store.load(buffer.iter().as_slice());

        return T { store };
    }

    /// Returns the first translation matching the provided key.
    /// Optionally a domain value may be used to specify the xliff file address.
    pub fn t(&self, domain: Option<&str>, key: &str) -> Option<&Unit> {
        match domain {
            None => {
                for group in self.store.groups.iter() {
                    match group.units.iter().find(|u| {
                        return u.id == String::from(key);
                    }) {
                        None => (),
                        Some(result) => return Some(result),
                    }
                }
            }
            Some(address) => {
                match self.store.groups.iter().find(|g| {
                    return g.address == String::from(address);
                }) {
                    None => (),
                    Some(group) => {
                        match group.units.iter().find(|u| {
                            return u.id == String::from(key);
                        }) {
                            None => (),
                            Some(result) => return Some(result),
                        }
                    }
                }
            }
        }

        return None;
    }
}