Debian Codegraph @

crates/mdbook-core/src/utils/toml_ext.rs

raw
1 //! Helper for working with toml types.
2
3 use toml::value::{Table, Value};
4
5 /// Helper for working with toml types.
6 pub(crate) trait TomlExt {
7 /// Read a dotted key.
8 fn read(&self, key: &str) -> Option<&Value>;
9 /// Insert with a dotted key.
10 fn insert(&mut self, key: &str, value: Value);
11 }
12
13 impl TomlExt for Value {
14 fn read(&self, key: &str) -> Option<&Value> {
15 if let Some((head, tail)) = split(key) {
16 self.get(head)?.read(tail)
17 } else {
18 self.get(key)
19 }
20 }
21
22 fn insert(&mut self, key: &str, value: Value) {
23 if !self.is_table() {
24 *self = Value::Table(Table::new());
25 }
26
27 let table = self.as_table_mut().expect("unreachable");
28
29 if let Some((head, tail)) = split(key) {
30 table
31 .entry(head)
32 .or_insert_with(|| Value::Table(Table::new()))
33 .insert(tail, value);
34 } else {
35 table.insert(key.to_string(), value);
36 }
37 }
38 }
39
40 fn split(key: &str) -> Option<(&str, &str)> {
41 let ix = key.find('.')?;
42
43 let (head, tail) = key.split_at(ix);
44 // splitting will leave the "."
45 let tail = &tail[1..];
46
47 Some((head, tail))
48 }
49
50 #[cfg(test)]
51 mod tests {
52 use super::*;
53
54 #[test]
55 fn read_simple_table() {
56 let src = "[table]";
57 let value: Value = toml::from_str(src).unwrap();
58
59 let got = value.read("table").unwrap();
60
61 assert!(got.is_table());
62 }
63
64 #[test]
65 fn read_nested_item() {
66 let src = "[table]\nnested=true";
67 let value: Value = toml::from_str(src).unwrap();
68
69 let got = value.read("table.nested").unwrap();
70
71 assert_eq!(got, &Value::Boolean(true));
72 }
73
74 #[test]
75 fn insert_item_at_top_level() {
76 let mut value = Value::Table(Table::default());
77 let item = Value::Boolean(true);
78
79 value.insert("first", item.clone());
80
81 assert_eq!(value.get("first").unwrap(), &item);
82 }
83
84 #[test]
85 fn insert_nested_item() {
86 let mut value = Value::Table(Table::default());
87 let item = Value::Boolean(true);
88
89 value.insert("first.second", item.clone());
90
91 let inserted = value.read("first.second").unwrap();
92 assert_eq!(inserted, &item);
93 }
94 }