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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use crate::error::Error;
use crate::value::Value;
use ordered_float::OrderedFloat;
use std::collections::HashMap;
use std::convert::TryInto;
use std::hash::Hash;

/// Specify how FromDynamic will treat unknown fields
/// when converting from Value to a given target type
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum UnknownFieldAction {
    /// Don't check, don't warn, don't raise an error
    Ignore,
    /// Emit a log::warn log
    Warn,
    /// Return an Error
    Deny,
}

impl Default for UnknownFieldAction {
    fn default() -> UnknownFieldAction {
        UnknownFieldAction::Warn
    }
}

/// Specify various options for FromDynamic::from_dynamic
#[derive(Copy, Clone, Debug, Default)]
pub struct FromDynamicOptions {
    pub unknown_fields: UnknownFieldAction,
    pub deprecated_fields: UnknownFieldAction,
}

impl FromDynamicOptions {
    pub fn flatten(self) -> Self {
        Self {
            unknown_fields: UnknownFieldAction::Ignore,
            ..self
        }
    }
}

/// The FromDynamic trait allows a type to construct itself from a Value.
/// This trait can be derived.
pub trait FromDynamic {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error>
    where
        Self: Sized;
}

impl FromDynamic for Value {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        Ok(value.clone())
    }
}

impl FromDynamic for ordered_float::NotNan<f64> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        let f = f64::from_dynamic(value, options)?;
        Ok(ordered_float::NotNan::new(f).map_err(|e| Error::Message(e.to_string()))?)
    }
}

impl FromDynamic for std::time::Duration {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        let f = f64::from_dynamic(value, options)?;
        Ok(std::time::Duration::from_secs_f64(f))
    }
}

impl<T: FromDynamic> FromDynamic for Box<T> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        let value = T::from_dynamic(value, options)?;
        Ok(Box::new(value))
    }
}

impl<T: FromDynamic> FromDynamic for std::sync::Arc<T> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        let value = T::from_dynamic(value, options)?;
        Ok(std::sync::Arc::new(value))
    }
}

impl<T: FromDynamic> FromDynamic for Option<T> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Null => Ok(None),
            value => Ok(Some(T::from_dynamic(value, options)?)),
        }
    }
}

impl<T: FromDynamic, const N: usize> FromDynamic for [T; N] {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Array(arr) => {
                let v = arr
                    .iter()
                    .map(|v| T::from_dynamic(v, options))
                    .collect::<Result<Vec<T>, Error>>()?;
                v.try_into().map_err(|v: Vec<T>| Error::ArraySizeMismatch {
                    vec_size: v.len(),
                    array_size: N,
                })
            }
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "array",
            }),
        }
    }
}

impl<K: FromDynamic + Eq + Hash, T: FromDynamic> FromDynamic for HashMap<K, T> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Object(obj) => {
                let mut map = HashMap::with_capacity(obj.len());
                for (k, v) in obj.iter() {
                    map.insert(K::from_dynamic(k, options)?, T::from_dynamic(v, options)?);
                }
                Ok(map)
            }
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "HashMap",
            }),
        }
    }
}

impl<T: FromDynamic> FromDynamic for Vec<T> {
    fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Array(arr) => Ok(arr
                .iter()
                .map(|v| T::from_dynamic(v, options))
                .collect::<Result<Vec<T>, Error>>()?),
            // lua uses tables for everything; we can end up here if we got an empty
            // table and treated it as an object. Allow that to stand-in for an empty
            // array instead.
            Value::Object(obj) if obj.is_empty() => Ok(vec![]),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "Vec",
            }),
        }
    }
}

impl FromDynamic for () {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Null => Ok(()),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "()",
            }),
        }
    }
}

impl FromDynamic for bool {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::Bool(b) => Ok(*b),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "bool",
            }),
        }
    }
}

impl FromDynamic for std::path::PathBuf {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::String(s) => Ok(s.into()),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "PathBuf",
            }),
        }
    }
}

impl FromDynamic for char {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::String(s) => {
                let mut iter = s.chars();
                let c = iter.next().ok_or_else(|| Error::CharFromWrongSizedString)?;
                if iter.next().is_some() {
                    Err(Error::CharFromWrongSizedString)
                } else {
                    Ok(c)
                }
            }
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "char",
            }),
        }
    }
}

impl FromDynamic for String {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::String(s) => Ok(s.to_string()),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "String",
            }),
        }
    }
}

macro_rules! int {
    ($($ty:ty),* $(,)?) => {
        $(
impl FromDynamic for $ty {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::I64(n) => match (*n).try_into() {
                Ok(n) => Ok(n),
                Err(err) => Err(Error::Message(err.to_string())),
            },
            Value::U64(n) => match (*n).try_into() {
                Ok(n) => Ok(n),
                Err(err) => Err(Error::Message(err.to_string())),
            },
            other => Err(Error::NoConversion{
                source_type:other.variant_name().to_string(),
                dest_type: stringify!($ty),
            })
        }
    }
}
        )*
    }
}

int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

impl FromDynamic for f32 {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::F64(OrderedFloat(n)) => Ok((*n) as f32),
            Value::I64(n) => Ok((*n) as f32),
            Value::U64(n) => Ok((*n) as f32),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "f32",
            }),
        }
    }
}

impl FromDynamic for f64 {
    fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result<Self, Error> {
        match value {
            Value::F64(OrderedFloat(n)) => Ok(*n),
            Value::I64(n) => Ok((*n) as f64),
            Value::U64(n) => Ok((*n) as f64),
            other => Err(Error::NoConversion {
                source_type: other.variant_name().to_string(),
                dest_type: "f64",
            }),
        }
    }
}