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
use super::{RhaiResult, fs};
use toml::{to_string_pretty, from_str};
use rhai::{Engine, Dynamic, Module};
fn read(path: &str) -> RhaiResult<Dynamic> {
let ctn = fs::read_file(path)?;
from_str(&ctn)
.map_err(|e| err!("toml: failed to deserialize {} error {:?}", path, e))
}
fn parse(ctn: &str) -> RhaiResult<Dynamic> {
from_str(&ctn)
.map_err(|e| err!("toml: failed to deserialize error {:?}", e))
}
fn write(path: &str, data: Dynamic) -> RhaiResult<()> {
let s = stringify(data)?;
fs::write_file_str(path, &s)
}
fn stringify(data: Dynamic) -> RhaiResult<String> {
let value = toml::Value::try_from(data)
.map_err(|e| err!(
"toml: failed to serialize error {:?}",
e
))?;
to_string_pretty(&value)
.map_err(|e| err!(
"toml: failed to serialize error {:?}",
e
))
}
pub fn add(engine: &mut Engine) {
let mut toml_mod = Module::new();
toml_mod.set_native_fn("read", read);
toml_mod.set_native_fn("parse", parse);
toml_mod.set_native_fn("write", write);
toml_mod.set_native_fn("stringify", stringify);
engine
.register_static_module("toml", toml_mod.into());
}