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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//! The native `toml` module for the [Rune Language].
//!
//! [Rune Language]: https://rune-rs.github.io
//!
//! ## Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! rune-modules = { version = "0.13.0", features = ["toml"] }
//! ```
//!
//! Install it into your context:
//!
//! ```rust
//! let mut context = rune::Context::with_default_modules()?;
//! context.install(rune_modules::toml::module(true)?)?;
//! # Ok::<_, rune::support::Error>(())
//! ```
//!
//! Use it in Rune:
//!
//! ```rust,ignore
//! use toml;
//!
//! fn main() {
//!     let data = toml::from_string("[hello]\nworld = 42");
//!     dbg(data);
//! }
//! ```

use rune::{ContextError, Module};
use rune::runtime::{Bytes, Value};
use rune::alloc::String;

/// Construct the `toml` module.
pub fn module(_stdio: bool) -> Result<Module, ContextError> {
    let mut module = Module::with_crate("toml")?;
    module.function_meta(from_bytes)?;
    module.function_meta(from_string)?;
    module.function_meta(to_string)?;
    module.function_meta(to_bytes)?;
    Ok(module)
}

pub mod de {
    //! Deserializer types for the toml module.

    use rune::{Any, Module, ContextError, vm_write};
    use rune::runtime::{Formatter, VmResult};
    use rune::alloc::fmt::TryWrite;

    pub fn module(_stdio: bool) -> Result<Module, ContextError> {
        let mut module = Module::with_crate_item("toml", ["de"])?;
        module.ty::<Error>()?;
        module.function_meta(Error::display)?;
        module.function_meta(Error::debug)?;
        Ok(module)
    }

    #[derive(Any)]
    #[rune(item = ::toml::de)]
    pub(crate) struct Error {
        pub(crate) error: toml::de::Error,
    }

    impl Error {
        #[rune::function(protocol = STRING_DISPLAY)]
        pub(crate) fn display(&self, f: &mut Formatter) -> VmResult<()> {
            vm_write!(f, "{}", self.error);
            VmResult::Ok(())
        }

        #[rune::function(protocol = STRING_DEBUG)]
        pub(crate) fn debug(&self, f: &mut Formatter) -> VmResult<()> {
            vm_write!(f, "{:?}", self.error);
            VmResult::Ok(())
        }
    }

    impl From<toml::de::Error> for Error {
        fn from(error: toml::de::Error) -> Self {
            Self { error }
        }
    }
}

pub mod ser {
    //! Serializer types for the toml module.

    use rune::{Any, Module, ContextError, vm_write};
    use rune::runtime::Formatter;
    use rune::alloc::fmt::TryWrite;

    pub fn module(_stdio: bool) -> Result<Module, ContextError> {
        let mut module = Module::with_crate_item("toml", ["ser"])?;
        module.ty::<Error>()?;
        module.function_meta(Error::display)?;
        module.function_meta(Error::debug)?;
        Ok(module)
    }

    #[derive(Any)]
    #[rune(item = ::toml::ser)]
    pub(crate) struct Error {
        pub(crate) error: toml::ser::Error,
    }

    impl Error {
        #[rune::function(vm_result, protocol = STRING_DISPLAY)]
        pub(crate) fn display(&self, f: &mut Formatter) {
            vm_write!(f, "{}", self.error);
        }

        #[rune::function(vm_result, protocol = STRING_DEBUG)]
        pub(crate) fn debug(&self, f: &mut Formatter) {
            vm_write!(f, "{:?}", self.error);
        }
    }

    impl From<toml::ser::Error> for Error {
        fn from(error: toml::ser::Error) -> Self {
            Self { error }
        }
    }
}

/// Convert bytes of TOML into a rune value.
#[rune::function(vm_result)]
fn from_bytes(bytes: &[u8]) -> Result<Value, Value> {
    let bytes = match std::str::from_utf8(bytes) {
        Ok(bytes) => bytes,
        Err(error) => return Err(rune::to_value(error).vm?),
    };

    match toml::from_str(bytes).map_err(de::Error::from) {
        Ok(value) => Ok(value),
        Err(error) => Err(rune::to_value(error).vm?),
    }
}

/// Convert a string of TOML into a rune value.
#[rune::function]
fn from_string(string: &str) -> Result<Value, de::Error> {
    Ok(toml::from_str(string)?)
}

/// Convert any value to a toml string.
#[rune::function(vm_result)]
fn to_string(value: Value) -> Result<String, ser::Error> {
    Ok(String::try_from(toml::to_string(&value)?).vm?)
}

/// Convert any value to toml bytes.
#[rune::function(vm_result)]
fn to_bytes(value: Value) -> Result<Bytes, ser::Error> {
    let string = String::try_from(toml::to_string(&value)?).vm?;
    Ok(Bytes::from_vec(string.into_bytes()))
}