1
use std::fmt;
2

            
3
use serde::{
4
    de::{Error, MapAccess, SeqAccess, Visitor},
5
    Deserialize, Deserializer,
6
};
7

            
8
use crate::{
9
    error::SpannedResult,
10
    value::{Map, Number, Value},
11
};
12

            
13
impl std::str::FromStr for Value {
14
    type Err = crate::error::SpannedError;
15

            
16
    /// Creates a value from a string reference.
17
4980
    fn from_str(s: &str) -> SpannedResult<Self> {
18
4980
        let mut de = super::Deserializer::from_str(s)?;
19

            
20
4980
        let val = Value::deserialize(&mut de).map_err(|e| de.span_error(e))?;
21
4698
        de.end().map_err(|e| de.span_error(e))?;
22

            
23
4694
        Ok(val)
24
4980
    }
25
}
26

            
27
impl<'de> Deserialize<'de> for Value {
28
333795
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
29
333795
    where
30
333795
        D: Deserializer<'de>,
31
333795
    {
32
333795
        deserializer.deserialize_any(ValueVisitor)
33
333795
    }
34
}
35

            
36
struct ValueVisitor;
37

            
38
impl<'de> Visitor<'de> for ValueVisitor {
39
    type Value = Value;
40

            
41
72894
    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42
72894
        write!(f, "a RON value")
43
72894
    }
44

            
45
1664
    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
46
1664
    where
47
1664
        E: Error,
48
1664
    {
49
1664
        Ok(Value::Bool(v))
50
1664
    }
51

            
52
556
    fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
53
556
    where
54
556
        E: Error,
55
556
    {
56
556
        Ok(Value::Number(Number::new(v)))
57
556
    }
58

            
59
548
    fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
60
548
    where
61
548
        E: Error,
62
548
    {
63
548
        Ok(Value::Number(Number::new(v)))
64
548
    }
65

            
66
548
    fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
67
548
    where
68
548
        E: Error,
69
548
    {
70
548
        Ok(Value::Number(Number::new(v)))
71
548
    }
72

            
73
548
    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
74
548
    where
75
548
        E: Error,
76
548
    {
77
548
        Ok(Value::Number(Number::new(v)))
78
548
    }
79

            
80
    #[cfg(feature = "integer128")]
81
274
    fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
82
274
    where
83
274
        E: Error,
84
274
    {
85
274
        Ok(Value::Number(Number::new(v)))
86
274
    }
87

            
88
218418
    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
89
218418
    where
90
218418
        E: Error,
91
218418
    {
92
218418
        Ok(Value::Number(Number::new(v)))
93
218418
    }
94

            
95
556
    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
96
556
    where
97
556
        E: Error,
98
556
    {
99
556
        Ok(Value::Number(Number::new(v)))
100
556
    }
101

            
102
548
    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
103
548
    where
104
548
        E: Error,
105
548
    {
106
548
        Ok(Value::Number(Number::new(v)))
107
548
    }
108

            
109
548
    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
110
548
    where
111
548
        E: Error,
112
548
    {
113
548
        Ok(Value::Number(Number::new(v)))
114
548
    }
115

            
116
    #[cfg(feature = "integer128")]
117
411
    fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
118
411
    where
119
411
        E: Error,
120
411
    {
121
411
        Ok(Value::Number(Number::new(v)))
122
411
    }
123

            
124
5431
    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
125
5431
    where
126
5431
        E: Error,
127
5431
    {
128
5431
        Ok(Value::Number(Number::new(v)))
129
5431
    }
130

            
131
5222
    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
132
5222
    where
133
5222
        E: Error,
134
5222
    {
135
5222
        Ok(Value::Number(Number::new(v)))
136
5222
    }
137

            
138
1688
    fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
139
1688
    where
140
1688
        E: Error,
141
1688
    {
142
1688
        Ok(Value::Char(v))
143
1688
    }
144

            
145
8864
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
146
8864
    where
147
8864
        E: Error,
148
8864
    {
149
8864
        self.visit_string(v.to_owned())
150
8864
    }
151

            
152
8888
    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
153
8888
    where
154
8888
        E: Error,
155
8888
    {
156
8888
        Ok(Value::String(v))
157
8888
    }
158

            
159
1648
    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
160
1648
    where
161
1648
        E: Error,
162
1648
    {
163
1648
        self.visit_byte_buf(v.to_vec())
164
1648
    }
165

            
166
2208
    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
167
2208
    where
168
2208
        E: Error,
169
2208
    {
170
2208
        Ok(Value::Bytes(v))
171
2208
    }
172

            
173
560
    fn visit_none<E>(self) -> Result<Self::Value, E>
174
560
    where
175
560
        E: Error,
176
560
    {
177
560
        Ok(Value::Option(None))
178
560
    }
179

            
180
3860
    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
181
3860
    where
182
3860
        D: Deserializer<'de>,
183
3860
    {
184
3860
        Ok(Value::Option(Some(Box::new(
185
3860
            deserializer.deserialize_any(ValueVisitor)?,
186
        ))))
187
3860
    }
188

            
189
3308
    fn visit_unit<E>(self) -> Result<Self::Value, E>
190
3308
    where
191
3308
        E: Error,
192
3308
    {
193
3308
        Ok(Value::Unit)
194
3308
    }
195

            
196
4
    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
197
4
    where
198
4
        D: Deserializer<'de>,
199
4
    {
200
4
        deserializer.deserialize_any(ValueVisitor)
201
4
    }
202

            
203
5510
    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
204
5510
    where
205
5510
        A: SeqAccess<'de>,
206
5510
    {
207
5510
        let mut vec = Vec::new();
208
5510
        if let Some(cap) = seq.size_hint() {
209
4
            vec.reserve_exact(cap);
210
5506
        }
211

            
212
14636
        while let Some(x) = seq.next_element()? {
213
9126
            vec.push(x);
214
9126
        }
215

            
216
4958
        Ok(Value::Seq(vec))
217
5510
    }
218

            
219
74290
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
220
74290
    where
221
74290
        A: MapAccess<'de>,
222
74290
    {
223
74290
        let mut res: Map = Map::new();
224

            
225
        #[cfg(feature = "indexmap")]
226
37964
        if let Some(cap) = map.size_hint() {
227
2
            res.0.reserve_exact(cap);
228
37962
        }
229

            
230
80122
        while let Some(entry) = map.next_entry::<Value, Value>()? {
231
5832
            res.insert(entry.0, entry.1);
232
5832
        }
233

            
234
4694
        Ok(Value::Map(res))
235
74290
    }
236
}
237

            
238
#[cfg(test)]
239
mod tests {
240
    use std::str::FromStr;
241

            
242
    use super::*;
243

            
244
36
    fn eval(s: &str) -> Value {
245
36
        s.parse().expect("Failed to parse")
246
36
    }
247

            
248
    #[test]
249
4
    fn test_none() {
250
4
        assert_eq!(eval("None"), Value::Option(None));
251
4
    }
252

            
253
    #[test]
254
4
    fn test_some() {
255
4
        assert_eq!(eval("Some(())"), Value::Option(Some(Box::new(Value::Unit))));
256
4
        assert_eq!(
257
4
            eval("Some  (  () )"),
258
4
            Value::Option(Some(Box::new(Value::Unit)))
259
4
        );
260
4
    }
261

            
262
    #[test]
263
4
    fn test_tuples_basic() {
264
4
        assert_eq!(
265
4
            eval("(3, 4.0, 5.0)"),
266
4
            Value::Seq(vec![
267
4
                Value::Number(Number::U8(3)),
268
4
                Value::Number(Number::F32(4.0.into())),
269
4
                Value::Number(Number::F32(5.0.into())),
270
4
            ],),
271
4
        );
272
4
    }
273

            
274
    #[test]
275
4
    fn test_tuples_ident() {
276
4
        assert_eq!(
277
4
            eval("(true, 3, 4, 5.0)"),
278
4
            Value::Seq(vec![
279
4
                Value::Bool(true),
280
4
                Value::Number(Number::U8(3)),
281
4
                Value::Number(Number::U8(4)),
282
4
                Value::Number(Number::F32(5.0.into())),
283
4
            ]),
284
4
        );
285
4
    }
286

            
287
    #[test]
288
4
    fn test_tuples_error() {
289
        use crate::de::{Error, Position, SpannedError};
290

            
291
4
        assert_eq!(
292
4
            Value::from_str("Foo:").unwrap_err(),
293
4
            SpannedError {
294
4
                code: Error::TrailingCharacters,
295
4
                position: Position { col: 4, line: 1 }
296
4
            },
297
4
        );
298
4
    }
299

            
300
    #[test]
301
4
    fn test_floats() {
302
4
        assert_eq!(
303
4
            eval("(inf, -inf, NaN)"),
304
4
            Value::Seq(vec![
305
4
                Value::Number(Number::new(std::f32::INFINITY)),
306
4
                Value::Number(Number::new(std::f32::NEG_INFINITY)),
307
4
                Value::Number(Number::new(std::f32::NAN)),
308
4
            ]),
309
4
        );
310
4
    }
311

            
312
    #[test]
313
4
    fn test_complex() {
314
4
        assert_eq!(
315
4
            eval(
316
4
                "Some([
317
4
    Room ( width: 20, height: 5, name: \"The Room\" ),
318
4

            
319
4
    (
320
4
        width: 10.0,
321
4
        height: 10.0,
322
4
        name: \"Another room\",
323
4
        enemy_levels: {
324
4
            \"Enemy1\": 3,
325
4
            \"Enemy2\": 5,
326
4
            \"Enemy3\": 7,
327
4
        },
328
4
    ),
329
4
])"
330
4
            ),
331
4
            Value::Option(Some(Box::new(Value::Seq(vec![
332
4
                Value::Map(
333
4
                    vec![
334
4
                        (
335
4
                            Value::String("width".to_owned()),
336
4
                            Value::Number(Number::U8(20)),
337
4
                        ),
338
4
                        (
339
4
                            Value::String("height".to_owned()),
340
4
                            Value::Number(Number::U8(5)),
341
4
                        ),
342
4
                        (
343
4
                            Value::String("name".to_owned()),
344
4
                            Value::String("The Room".to_owned()),
345
4
                        ),
346
4
                    ]
347
4
                    .into_iter()
348
4
                    .collect(),
349
4
                ),
350
4
                Value::Map(
351
4
                    vec![
352
4
                        (
353
4
                            Value::String("width".to_owned()),
354
4
                            Value::Number(Number::F32(10.0.into())),
355
4
                        ),
356
4
                        (
357
4
                            Value::String("height".to_owned()),
358
4
                            Value::Number(Number::F32(10.0.into())),
359
4
                        ),
360
4
                        (
361
4
                            Value::String("name".to_owned()),
362
4
                            Value::String("Another room".to_owned()),
363
4
                        ),
364
4
                        (
365
4
                            Value::String("enemy_levels".to_owned()),
366
4
                            Value::Map(
367
4
                                vec![
368
4
                                    (
369
4
                                        Value::String("Enemy1".to_owned()),
370
4
                                        Value::Number(Number::U8(3)),
371
4
                                    ),
372
4
                                    (
373
4
                                        Value::String("Enemy2".to_owned()),
374
4
                                        Value::Number(Number::U8(5)),
375
4
                                    ),
376
4
                                    (
377
4
                                        Value::String("Enemy3".to_owned()),
378
4
                                        Value::Number(Number::U8(7)),
379
4
                                    ),
380
4
                                ]
381
4
                                .into_iter()
382
4
                                .collect(),
383
4
                            ),
384
4
                        ),
385
4
                    ]
386
4
                    .into_iter()
387
4
                    .collect(),
388
4
                ),
389
4
            ]))))
390
4
        );
391
4
    }
392

            
393
    #[test]
394
4
    fn test_struct() {
395
4
        assert_eq!(
396
4
            eval("(a:42)"),
397
4
            Value::Map(
398
4
                [(
399
4
                    Value::String(String::from("a")),
400
4
                    Value::Number(Number::U8(42))
401
4
                )]
402
4
                .into_iter()
403
4
                .collect()
404
4
            ),
405
4
        );
406
4
        assert_eq!(
407
4
            eval("(r#a:42)"),
408
4
            Value::Map(
409
4
                [(
410
4
                    Value::String(String::from("a")),
411
4
                    Value::Number(Number::U8(42))
412
4
                )]
413
4
                .into_iter()
414
4
                .collect()
415
4
            ),
416
4
        );
417
4
        assert_eq!(
418
4
            "(r#:42)".parse::<Value>().unwrap_err(),
419
4
            crate::error::SpannedError {
420
4
                code: crate::Error::ExpectedString,
421
4
                position: crate::error::Position { line: 1, col: 4 },
422
4
            },
423
4
        );
424

            
425
        // Check for a failure in Deserializer::check_struct_type
426
        // - opening brace triggers the struct type check
427
        // - unclosed block comment fails the whitespace skip
428
4
        assert_eq!(
429
4
            "( /*".parse::<Value>().unwrap_err(),
430
4
            crate::error::SpannedError {
431
4
                code: crate::Error::UnclosedBlockComment,
432
4
                position: crate::error::Position { line: 1, col: 5 },
433
4
            },
434
4
        );
435
4
    }
436
}