1use std::path::PathBuf;
2use stardict_lib::{no_cache, StarDict, StarDictStd};
3
4pub struct WrapperDict {
5 pub std_dict: StarDictStd,
6}
7
8impl WrapperDict {
9 pub fn init(path: impl Into<PathBuf>) -> WrapperDict {
10 let dict = no_cache(path).unwrap();
11 return WrapperDict {
12 std_dict: dict,
13 };
14 }
15
16 pub fn translate(&mut self, word: &str) -> Option<String> {
17 if let Ok(result) = self.std_dict.lookup(word) {
18 if let None = result {
19 return None;
20 } else if let Some(defs) = result {
21 if defs.len() == 0 {
22 return None;
23 }
24
25 let result = String::new();
26 for def in &defs[0].segments {
27 return if let Some(pos) = def.text.find(';').or(def.text.find('\n')) {
28 let output = &def.text[..pos];
29 Some(output.into())
30 } else {
31 Some(def.text.clone())
32 }
33 }
34
35 return Some(result);
36 } else {
37 unreachable!()
38 };
39 } else {
40 return None;
41 }
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn test_translate() {
51 let mut dict = WrapperDict::init("/Users/phodal/Downloads/stardict-ncce-ce-2.4.2");
52 let result = dict.translate("对齐");
53 assert_eq!(result, Some("hello".to_string()));
54 }
55}