kobo_db_tools/export/
dictionary.rs1use crate::export::{Export, ExportError};
2use crate::model::DictionaryWord;
3
4impl Export for [DictionaryWord] {
5 fn to_csv(&self) -> Result<String, ExportError> {
6 let mut wtr = csv::Writer::from_writer(vec![]);
7 for word in self {
8 wtr.serialize(word)?;
9 }
10 Ok(String::from_utf8(wtr.into_inner()?)?)
11 }
12
13 fn to_md(&self) -> Result<String, ExportError> {
14 let mut buffer = Vec::new();
15 use std::io::Write;
16
17 writeln!(buffer, "| Term | Language | Session ID |")?;
18 writeln!(buffer, "|------|----------|------------|")?;
19
20 for word in self {
21 let session_id_str = word
22 .session_id()
23 .map(|id| id.to_string())
24 .unwrap_or_else(|| "N/A".to_string());
25
26 writeln!(
27 buffer,
28 "| {} | {} | {} |",
29 word.term(),
30 word.lang(),
31 session_id_str
32 )?;
33 }
34 Ok(String::from_utf8(buffer)?)
35 }
36
37 fn to_json(&self) -> Result<String, ExportError> {
38 serde_json::to_string(self).map_err(ExportError::JsonToString)
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45 use crate::model::DictionaryWord;
46 use uuid::Uuid;
47
48 fn get_test_words() -> Vec<DictionaryWord> {
49 vec![
50 DictionaryWord::new("hello".to_string(), "en".to_string(), Some(Uuid::nil())),
51 DictionaryWord::new("world".to_string(), "en".to_string(), None),
52 ]
53 }
54
55 #[test]
56 fn test_dict_to_csv() {
57 let words = get_test_words();
58 let expected = [
59 "term,lang,session_id",
60 "hello,en,00000000-0000-0000-0000-000000000000",
61 "world,en,",
62 "",
63 ].join("\n");
64 assert_eq!(words.to_csv().unwrap(), expected);
65 }
66
67 #[test]
68 fn test_dict_to_md() {
69 let words = get_test_words();
70 let expected = [
71 "| Term | Language | Session ID |",
72 "|------|----------|------------|",
73 "| hello | en | 00000000-0000-0000-0000-000000000000 |",
74 "| world | en | N/A |",
75 "",
76 ].join("\n");
77 assert_eq!(words.to_md().unwrap(), expected);
78 }
79
80 #[test]
81 fn test_dict_to_json() {
82 let words = get_test_words();
83 let expected = serde_json::to_string(&words).unwrap();
84 assert_eq!(words.to_json().unwrap(), expected);
85 }
86}