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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Clone)]
pub struct Language {
name: String,
short_name: String,
strings: HashMap::<String, String>
}
impl Language {
pub fn new(name: String, short_name: String, strings: HashMap::<String, String>) -> Self {
Self { name, short_name, strings }
}
pub fn new_from_string(json: &str) -> Result<Self, String> {
match serde_json::from_str(json) {
Ok(lang) => Ok(lang),
Err(e) => Err(e.to_string())
}
}
pub fn new_from_file(path: &str) -> Result<Self, String> {
match std::fs::read_to_string(path) {
Ok(json) => {
Self::new_from_string(&json)
},
Err(e) => {
Err(e.to_string())
}
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn short_name(&self) -> &str {
&self.short_name
}
pub fn get(&self, name: &str) -> Option<String> {
self.strings.get(name).cloned()
}
}
#[cfg(test)]
mod test_token {
use super::*;
use crate as embedded_lang;
use crate::embedded_language;
#[test]
fn test_new_from_string() {
if let Ok(s) = std::fs::read_to_string("examples/en.lang.json") {
let lang = Language::new_from_string(&s).unwrap();
assert_eq!(lang.short_name(), "en");
}
}
#[test]
fn test_new_from_file() {
let lang = Language::new_from_file("examples/en.lang.json").unwrap();
assert_eq!(lang.short_name(), "en");
}
#[test]
fn test_short_name() {
let lang = embedded_language!("../examples/en.lang.json");
assert_eq!(lang.short_name(), "en");
}
#[test]
fn test_name() {
let lang = embedded_language!("../examples/en.lang.json");
assert_eq!(lang.name(), "English");
}
#[test]
fn test_get() {
let lang = embedded_language!("../examples/en.lang.json");
assert_eq!(lang.get("hello_msg"), Some("hello world!".to_string()));
assert_eq!(lang.get("goodbye_msg"), None);
}
}