1
//! Value module.
2

            
3
use std::{borrow::Cow, cmp::Eq, hash::Hash};
4

            
5
use serde::{
6
    de::{DeserializeOwned, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor},
7
    forward_to_deserialize_any,
8
};
9

            
10
use crate::{de::Error, error::Result};
11

            
12
mod map;
13
mod number;
14
pub(crate) mod raw;
15

            
16
pub use map::Map;
17
pub use number::{Number, F32, F64};
18
#[allow(clippy::useless_attribute, clippy::module_name_repetitions)]
19
pub use raw::RawValue;
20

            
21
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
22
pub enum Value {
23
    Bool(bool),
24
    Char(char),
25
    Map(Map),
26
    Number(Number),
27
    Option(Option<Box<Value>>),
28
    String(String),
29
    Bytes(Vec<u8>),
30
    Seq(Vec<Value>),
31
    Unit,
32
}
33

            
34
impl From<bool> for Value {
35
12
    fn from(value: bool) -> Self {
36
12
        Self::Bool(value)
37
12
    }
38
}
39

            
40
impl From<char> for Value {
41
8
    fn from(value: char) -> Self {
42
8
        Self::Char(value)
43
8
    }
44
}
45

            
46
impl<K: Into<Value>, V: Into<Value>> FromIterator<(K, V)> for Value {
47
4
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
48
4
        Self::Map(iter.into_iter().collect())
49
4
    }
50
}
51

            
52
impl From<Map> for Value {
53
4
    fn from(value: Map) -> Self {
54
4
        Self::Map(value)
55
4
    }
56
}
57

            
58
impl<T: Into<Number>> From<T> for Value {
59
228
    fn from(value: T) -> Self {
60
228
        Self::Number(value.into())
61
228
    }
62
}
63

            
64
impl<T: Into<Value>> From<Option<T>> for Value {
65
16
    fn from(value: Option<T>) -> Self {
66
16
        Self::Option(value.map(Into::into).map(Box::new))
67
16
    }
68
}
69

            
70
impl<'a> From<&'a str> for Value {
71
132
    fn from(value: &'a str) -> Self {
72
132
        String::from(value).into()
73
132
    }
74
}
75

            
76
impl<'a> From<Cow<'a, str>> for Value {
77
4
    fn from(value: Cow<'a, str>) -> Self {
78
4
        String::from(value).into()
79
4
    }
80
}
81

            
82
impl From<String> for Value {
83
140
    fn from(value: String) -> Self {
84
140
        Self::String(value)
85
140
    }
86
}
87

            
88
/// Special case to allow `Value::from(b"byte string")`
89
impl<const N: usize> From<&'static [u8; N]> for Value {
90
4
    fn from(value: &'static [u8; N]) -> Self {
91
4
        Self::Bytes(Vec::from(*value))
92
4
    }
93
}
94

            
95
impl<T: Into<Value>> FromIterator<T> for Value {
96
16
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
97
16
        Self::Seq(iter.into_iter().map(Into::into).collect())
98
16
    }
99
}
100

            
101
impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value {
102
4
    fn from(value: &'a [T]) -> Self {
103
4
        value.iter().map(Clone::clone).map(Into::into).collect()
104
4
    }
105
}
106

            
107
impl<T: Into<Value>> From<Vec<T>> for Value {
108
8
    fn from(value: Vec<T>) -> Self {
109
8
        value.into_iter().collect()
110
8
    }
111
}
112

            
113
impl From<()> for Value {
114
4
    fn from(_value: ()) -> Self {
115
4
        Value::Unit
116
4
    }
117
}
118

            
119
impl Value {
120
    /// Tries to deserialize this [`Value`] into `T`.
121
48
    pub fn into_rust<T>(self) -> Result<T>
122
48
    where
123
48
        T: DeserializeOwned,
124
48
    {
125
48
        T::deserialize(self)
126
48
    }
127
}
128

            
129
/// Deserializer implementation for RON [`Value`].
130
/// This does not support enums (because [`Value`] does not store them).
131
impl<'de> Deserializer<'de> for Value {
132
    type Error = Error;
133

            
134
    forward_to_deserialize_any! {
135
        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
136
        byte_buf option unit unit_struct newtype_struct seq tuple
137
        tuple_struct map struct enum identifier ignored_any
138
    }
139

            
140
    #[cfg(feature = "integer128")]
141
    forward_to_deserialize_any! {
142
        i128 u128
143
    }
144

            
145
368
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
146
368
    where
147
368
        V: Visitor<'de>,
148
368
    {
149
24
        match self {
150
16
            Value::Bool(b) => visitor.visit_bool(b),
151
40
            Value::Char(c) => visitor.visit_char(c),
152
28
            Value::Map(m) => {
153
28
                let old_len = m.len();
154
28

            
155
28
                let mut items: Vec<(Value, Value)> = m.into_iter().collect();
156
28
                items.reverse();
157

            
158
28
                let value = visitor.visit_map(MapAccessor {
159
28
                    items: &mut items,
160
28
                    value: None,
161
28
                })?;
162

            
163
20
                if items.is_empty() {
164
12
                    Ok(value)
165
                } else {
166
4
                    Err(Error::ExpectedDifferentLength {
167
4
                        expected: format!("a map of length {}", old_len - items.len()),
168
4
                        found: old_len,
169
4
                    })
170
                }
171
            }
172
124
            Value::Number(number) => number.visit(visitor),
173
16
            Value::Option(Some(o)) => visitor.visit_some(*o),
174
8
            Value::Option(None) => visitor.visit_none(),
175
60
            Value::String(s) => visitor.visit_string(s),
176
16
            Value::Bytes(b) => visitor.visit_byte_buf(b),
177
48
            Value::Seq(mut seq) => {
178
48
                let old_len = seq.len();
179
48

            
180
48
                seq.reverse();
181
48
                let value = visitor.visit_seq(SeqAccessor { seq: &mut seq })?;
182

            
183
44
                if seq.is_empty() {
184
36
                    Ok(value)
185
                } else {
186
8
                    Err(Error::ExpectedDifferentLength {
187
8
                        expected: format!("a sequence of length {}", old_len - seq.len()),
188
8
                        found: old_len,
189
8
                    })
190
                }
191
            }
192
12
            Value::Unit => visitor.visit_unit(),
193
        }
194
364
    }
195
}
196

            
197
struct SeqAccessor<'a> {
198
    seq: &'a mut Vec<Value>,
199
}
200

            
201
impl<'a, 'de> SeqAccess<'de> for SeqAccessor<'a> {
202
    type Error = Error;
203

            
204
112
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
205
112
    where
206
112
        T: DeserializeSeed<'de>,
207
112
    {
208
112
        // The `Vec` is reversed, so we can pop to get the originally first element
209
112
        self.seq
210
112
            .pop()
211
112
            .map_or(Ok(None), |v| seed.deserialize(v).map(Some))
212
112
    }
213

            
214
8
    fn size_hint(&self) -> Option<usize> {
215
8
        Some(self.seq.len())
216
8
    }
217
}
218

            
219
struct MapAccessor<'a> {
220
    items: &'a mut Vec<(Value, Value)>,
221
    value: Option<Value>,
222
}
223

            
224
impl<'a, 'de> MapAccess<'de> for MapAccessor<'a> {
225
    type Error = Error;
226

            
227
40
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
228
40
    where
229
40
        K: DeserializeSeed<'de>,
230
40
    {
231
40
        // The `Vec` is reversed, so we can pop to get the originally first element
232
40
        match self.items.pop() {
233
28
            Some((key, value)) => {
234
28
                self.value = Some(value);
235
28
                seed.deserialize(key).map(Some)
236
            }
237
12
            None => Ok(None),
238
        }
239
40
    }
240

            
241
    #[allow(clippy::panic)]
242
32
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
243
32
    where
244
32
        V: DeserializeSeed<'de>,
245
32
    {
246
32
        match self.value.take() {
247
28
            Some(value) => seed.deserialize(value),
248
4
            None => panic!("Contract violation: value before key"),
249
        }
250
28
    }
251

            
252
2
    fn size_hint(&self) -> Option<usize> {
253
2
        Some(self.items.len())
254
2
    }
255
}
256

            
257
#[cfg(test)]
258
mod tests {
259
    use std::{collections::BTreeMap, fmt::Debug};
260

            
261
    use serde::Deserialize;
262

            
263
    use super::*;
264

            
265
64
    fn assert_same<'de, T>(s: &'de str)
266
64
    where
267
64
        T: Debug + Deserialize<'de> + PartialEq,
268
64
    {
269
        use crate::de::from_str;
270

            
271
64
        let direct: T = from_str(s).unwrap();
272
64
        let value: Value = from_str(s).unwrap();
273
64
        let de = T::deserialize(value.clone()).unwrap();
274
64

            
275
64
        assert_eq!(direct, de, "Deserialization for {:?} is not the same", s);
276

            
277
64
        let value_roundtrip = Value::deserialize(value.clone()).unwrap();
278
64
        assert_eq!(value_roundtrip, value);
279
64
    }
280

            
281
8
    fn assert_same_bytes<'de, T>(s: &'de [u8])
282
8
    where
283
8
        T: Debug + Deserialize<'de> + PartialEq,
284
8
    {
285
        use crate::de::from_bytes;
286

            
287
8
        let direct: T = from_bytes(s).unwrap();
288
8
        let value: Value = from_bytes(s).unwrap();
289
8
        let de = T::deserialize(value.clone()).unwrap();
290
8

            
291
8
        assert_eq!(direct, de, "Deserialization for {:?} is not the same", s);
292

            
293
8
        let value_roundtrip = Value::deserialize(value.clone()).unwrap();
294
8
        assert_eq!(value_roundtrip, value);
295
8
    }
296

            
297
    #[test]
298
4
    fn boolean() {
299
4
        assert_same::<bool>("true");
300
4
        assert_same::<bool>("false");
301
4

            
302
4
        assert_eq!(Value::from(true), Value::Bool(true));
303
4
        assert_eq!(Value::from(false), Value::Bool(false));
304
4
    }
305

            
306
    #[test]
307
4
    fn float() {
308
4
        assert_same::<f64>("0.123");
309
4
        assert_same::<f64>("-4.19");
310
4

            
311
4
        assert_eq!(
312
4
            Value::from(42_f32),
313
4
            Value::Number(Number::F32(42_f32.into()))
314
4
        );
315
4
        assert_eq!(
316
4
            Value::from(42_f64),
317
4
            Value::Number(Number::F64(42_f64.into()))
318
4
        );
319
4
    }
320

            
321
    #[test]
322
4
    fn int() {
323
4
        assert_same::<u32>("626");
324
4
        assert_same::<i32>("-50");
325
4

            
326
4
        assert_eq!(Value::from(0_i8), Value::Number(Number::I8(0)));
327
4
        assert_eq!(Value::from(0_i16), Value::Number(Number::I16(0)));
328
4
        assert_eq!(Value::from(0_i32), Value::Number(Number::I32(0)));
329
4
        assert_eq!(Value::from(0_i64), Value::Number(Number::I64(0)));
330
        #[cfg(feature = "integer128")]
331
2
        assert_eq!(Value::from(0_i128), Value::Number(Number::I128(0)));
332
4
        assert_eq!(Value::from(0_u8), Value::Number(Number::U8(0)));
333
4
        assert_eq!(Value::from(0_u16), Value::Number(Number::U16(0)));
334
4
        assert_eq!(Value::from(0_u32), Value::Number(Number::U32(0)));
335
4
        assert_eq!(Value::from(0_u64), Value::Number(Number::U64(0)));
336
        #[cfg(feature = "integer128")]
337
2
        assert_eq!(Value::from(0_u128), Value::Number(Number::U128(0)));
338
4
    }
339

            
340
    #[test]
341
4
    fn char() {
342
4
        assert_same::<char>("'4'");
343
4
        assert_same::<char>("'c'");
344
4

            
345
4
        assert_eq!(Value::from('🦀'), Value::Char('🦀'));
346
4
    }
347

            
348
    #[test]
349
4
    fn string() {
350
4
        assert_same::<String>(r#""hello world""#);
351
4
        assert_same::<String>(r#""this is a Rusty 🦀 string""#);
352
4
        assert_same::<String>(r#""this is now valid UTF-8 \xf0\x9f\xa6\x80""#);
353
4

            
354
4
        assert_eq!(Value::from("slice"), Value::String(String::from("slice")));
355
4
        assert_eq!(
356
4
            Value::from(String::from("string")),
357
4
            Value::String(String::from("string"))
358
4
        );
359
4
        assert_eq!(
360
4
            Value::from(Cow::Borrowed("cow")),
361
4
            Value::String(String::from("cow"))
362
4
        );
363
4
    }
364

            
365
    #[test]
366
4
    fn bytes() {
367
4
        assert_same_bytes::<serde_bytes::ByteBuf>(br#"b"hello world""#);
368
4
        assert_same_bytes::<serde_bytes::ByteBuf>(
369
4
            br#"b"this is not valid UTF-8 \xf8\xa1\xa1\xa1\xa1""#,
370
4
        );
371
4

            
372
4
        assert_eq!(Value::from(b"bytes"), Value::Bytes(Vec::from(*b"bytes")));
373
4
    }
374

            
375
    #[test]
376
4
    fn map() {
377
4
        assert_same::<BTreeMap<char, String>>(
378
4
            "{
379
4
'a': \"Hello\",
380
4
'b': \"Bye\",
381
4
        }",
382
4
        );
383
4

            
384
4
        assert_eq!(Value::from(Map::new()), Value::Map(Map::new()));
385
4
        assert_eq!(
386
4
            Value::from_iter([("a", 42)]),
387
4
            Value::Map({
388
4
                let mut map = Map::new();
389
4
                map.insert(Value::from("a"), Value::from(42));
390
4
                map
391
4
            })
392
4
        );
393
4
    }
394

            
395
    #[test]
396
4
    fn option() {
397
4
        assert_same::<Option<char>>("Some('a')");
398
4
        assert_same::<Option<char>>("None");
399
4

            
400
4
        assert_eq!(Value::from(Option::<bool>::None), Value::Option(None));
401
4
        assert_eq!(
402
4
            Value::from(Some(false)),
403
4
            Value::Option(Some(Box::new(Value::Bool(false))))
404
4
        );
405
4
        assert_eq!(
406
4
            Value::from(Some(Option::<bool>::None)),
407
4
            Value::Option(Some(Box::new(Value::Option(None))))
408
4
        );
409
4
    }
410

            
411
    #[test]
412
4
    fn seq() {
413
4
        assert_same::<Vec<f64>>("[1.0, 2.0, 3.0, 4.0]");
414
4

            
415
4
        assert_eq!(
416
4
            Value::from([-1_i8, 2, -3].as_slice()),
417
4
            Value::Seq(vec![
418
4
                Value::from(-1_i8),
419
4
                Value::from(2_i8),
420
4
                Value::from(-3_i8)
421
4
            ])
422
4
        );
423
4
        assert_eq!(
424
4
            Value::from(vec![-1_i8, 2, -3]),
425
4
            Value::Seq(vec![
426
4
                Value::from(-1_i8),
427
4
                Value::from(2_i8),
428
4
                Value::from(-3_i8)
429
4
            ])
430
4
        );
431
4
        assert_eq!(
432
4
            Value::from_iter([-1_i8, 2, -3]),
433
4
            Value::Seq(vec![
434
4
                Value::from(-1_i8),
435
4
                Value::from(2_i8),
436
4
                Value::from(-3_i8)
437
4
            ])
438
4
        );
439
4
    }
440

            
441
    #[test]
442
4
    fn unit() {
443
4
        assert_same::<()>("()");
444
4

            
445
4
        assert_eq!(Value::from(()), Value::Unit);
446
4
    }
447

            
448
    #[test]
449
    #[should_panic(expected = "Contract violation: value before key")]
450
4
    fn map_access_contract_violation() {
451
        struct BadVisitor;
452

            
453
        impl<'de> Visitor<'de> for BadVisitor {
454
            type Value = ();
455

            
456
            // GRCOV_EXCL_START
457
            fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
458
                fmt.write_str("a map")
459
            }
460
            // GRCOV_EXCL_STOP
461

            
462
4
            fn visit_map<A: serde::de::MapAccess<'de>>(
463
4
                self,
464
4
                mut map: A,
465
4
            ) -> Result<Self::Value, A::Error> {
466
4
                map.next_value::<()>()
467
4
            }
468
        }
469

            
470
4
        let value = Value::Map([("a", 42)].into_iter().collect());
471
4
        let _ = value.deserialize_map(BadVisitor);
472
4
    }
473

            
474
    #[test]
475
4
    fn transparent_value_newtype() {
476
        struct NewtypeDeserializer;
477

            
478
        impl<'de> Deserializer<'de> for NewtypeDeserializer {
479
            type Error = Error;
480

            
481
4
            fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
482
4
                visitor.visit_newtype_struct(serde::de::value::CharDeserializer::new('🦀'))
483
4
            }
484

            
485
            // GRCOV_EXCL_START
486
            forward_to_deserialize_any! {
487
                bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string
488
                bytes byte_buf option unit unit_struct newtype_struct seq tuple
489
                tuple_struct map struct enum identifier ignored_any
490
            }
491

            
492
            #[cfg(feature = "integer128")]
493
            forward_to_deserialize_any! { i128 u128 }
494
            // GRCOV_EXCL_STOP
495
        }
496

            
497
4
        assert_eq!(
498
4
            Value::deserialize(NewtypeDeserializer).unwrap(),
499
4
            Value::from('🦀')
500
4
        );
501
4
    }
502
}