1
use alloc::borrow::Cow;
2
use alloc::vec::Vec;
3
use core::fmt::Display;
4
use core::str::{self, FromStr};
5

            
6
use crate::parser::{Config, Error, ErrorKind, Event, EventKind, Name, Nested, Parser, Primitive};
7
use crate::tokenizer::Integer;
8
use crate::writer::{self, Writer};
9

            
10
/// A value with a static lifetime.
11
pub type OwnedValue = Value<'static>;
12

            
13
/// A value representable by Rsn.
14
#[derive(Debug, Clone, PartialEq)]
15
pub enum Value<'a> {
16
    /// An integer.
17
    Integer(Integer),
18
    /// A floating point number.
19
    Float(f64),
20
    /// A boolean.
21
    Bool(bool),
22
    /// A character.
23
    Char(char),
24
    /// A byte.
25
    Byte(u8),
26
    /// An identifier (name).
27
    Identifier(Cow<'a, str>),
28
    /// A string.
29
    String(Cow<'a, str>),
30
    /// A byte string.
31
    Bytes(Cow<'a, [u8]>),
32
    /// A named structure.
33
    Named(Named<'a>),
34
    /// A tuple of values.
35
    Tuple(List<'a>),
36
    /// An array of values.
37
    Array(List<'a>),
38
    /// A collection of key-value pairs.
39
    Map(Map<'a>),
40
}
41

            
42
macro_rules! as_integer {
43
    ($name:ident, $ty:ty) => {
44
        /// Returns this value as a
45
        #[doc = stringify!($type)]
46
        /// if the value is an integer that can fit in a
47
        #[doc = stringify!($type)]
48
        #[must_use]
49
12
        pub fn $name(&self) -> Option<$ty> {
50
12
            let Self::Integer(value) = self else {
51
                return None;
52
            };
53

            
54
12
            value.$name()
55
12
        }
56
    };
57
}
58

            
59
impl<'a> Value<'a> {
60
    as_integer!(as_u8, u8);
61

            
62
    as_integer!(as_u16, u16);
63

            
64
    as_integer!(as_u32, u32);
65

            
66
    as_integer!(as_u64, u64);
67

            
68
    as_integer!(as_u128, u128);
69

            
70
    as_integer!(as_usize, usize);
71

            
72
    as_integer!(as_i8, i8);
73

            
74
    as_integer!(as_i16, i16);
75

            
76
    as_integer!(as_i32, i32);
77

            
78
    as_integer!(as_i64, i64);
79

            
80
    as_integer!(as_i128, i128);
81

            
82
    as_integer!(as_isize, isize);
83

            
84
    /// Parses `source` as a [`Value`].
85
    ///
86
    /// # Errors
87
    ///
88
    /// Returns any error encountered while parsing `source`.
89
    pub fn from_str(source: &'a str, config: Config) -> Result<Self, Error> {
90
        let mut parser = Parser::new(source, config.include_comments(false));
91
        Self::parse(&mut parser)
92
    }
93

            
94
    /// Returns a value representing the unit type.
95
    #[must_use]
96
    pub const fn unit() -> Self {
97
        Self::Tuple(List::new())
98
    }
99

            
100
    fn parse(parser: &mut Parser<'a>) -> Result<Self, Error> {
101
        let event = parser.next().transpose()?.ok_or_else(|| {
102
            Error::new(
103
                parser.current_offset()..parser.current_offset(),
104
                ErrorKind::UnexpectedEof,
105
            )
106
        })?;
107
        Self::from_parser_event(event, parser)
108
    }
109

            
110
    fn from_parser_event(event: Event<'a>, parser: &mut Parser<'a>) -> Result<Self, Error> {
111
        match event.kind {
112
            EventKind::BeginNested {
113
                name,
114
                kind: kind @ (Nested::Tuple | Nested::List),
115
            } => Self::parse_sequence(name, parser, kind),
116
            EventKind::BeginNested {
117
                name,
118
                kind: Nested::Map,
119
            } => Self::parse_map(name, parser),
120
            EventKind::Primitive(primitive) => match primitive {
121
                Primitive::Bool(value) => Ok(Value::Bool(value)),
122
                Primitive::Integer(value) => Ok(Value::Integer(value)),
123
                Primitive::Float(value) => Ok(Value::Float(value)),
124
                Primitive::Char(value) => Ok(Value::Char(value)),
125
                Primitive::String(value) => Ok(Value::String(value)),
126
                Primitive::Identifier(value) => Ok(Value::Identifier(Cow::Borrowed(value))),
127
                Primitive::Bytes(value) => Ok(Value::Bytes(value)),
128
            },
129
            EventKind::Comment(_) => unreachable!("disabled in parser"),
130
            EventKind::EndNested => unreachable!("Parser would error"),
131
        }
132
    }
133

            
134
    fn parse_sequence(
135
        name: Option<Name<'a>>,
136
        parser: &mut Parser<'a>,
137
        kind: Nested,
138
    ) -> Result<Self, Error> {
139
        let mut list = List::default();
140
        loop {
141
            let event = parser.next().expect("will error or have another event")?;
142
            if matches!(event.kind, EventKind::EndNested) {
143
                if let Some(name) = name {
144
                    return Ok(Self::Named(Named {
145
                        name: Cow::Borrowed(name.name),
146
                        contents: StructContents::Tuple(list),
147
                    }));
148
                }
149

            
150
                match kind {
151
                    Nested::List => return Ok(Self::Array(list)),
152
                    Nested::Tuple => return Ok(Self::Tuple(list)),
153
                    Nested::Map => unreachable!("parse_sequence isn't called on maps"),
154
                }
155
            } else {
156
                list.0.push(Self::from_parser_event(event, parser)?);
157
            }
158
        }
159
    }
160

            
161
    fn parse_map(name: Option<Name<'a>>, parser: &mut Parser<'a>) -> Result<Self, Error> {
162
        let mut map = Map::default();
163
        loop {
164
            let event = parser.next().expect("will error or have another event")?;
165
            if matches!(event.kind, EventKind::EndNested) {
166
                if let Some(name) = name {
167
                    return Ok(Self::Named(Named {
168
                        name: Cow::Borrowed(name.name),
169
                        contents: StructContents::Map(map),
170
                    }));
171
                }
172

            
173
                return Ok(Self::Map(map));
174
            }
175

            
176
            let key = Self::from_parser_event(event, parser)?;
177
            let value = Self::from_parser_event(
178
                parser.next().expect("will error or have another event")?,
179
                parser,
180
            )?;
181

            
182
            map.0.push((key, value));
183
        }
184
    }
185

            
186
    /// Creates a value by serializing `value` using Serde.
187
    ///
188
    /// # Errors
189
    ///
190
    /// Returns an error if the `value` cannot be represented losslessly or if
191
    /// any errors occur from `Serializer` implementations.
192
    #[cfg(feature = "serde")]
193
1
    pub fn from_serialize<S: ::serde::Serialize>(value: &S) -> Result<Self, ToValueError> {
194
1
        value.serialize(serde::ValueSerializer)
195
1
    }
196

            
197
    /// Deserializes `self` as `D` using Serde.
198
    ///
199
    /// # Errors
200
    ///
201
    /// Returns an error if `self` cannot be deserialized as `D`.
202
    #[cfg(feature = "serde")]
203
1
    pub fn to_deserialize<D: ::serde::Deserialize<'a>>(&self) -> Result<D, serde::FromValueError> {
204
1
        D::deserialize(serde::ValueDeserializer(self))
205
1
    }
206

            
207
    /// Returns the owned version of `self`, copying any borrowed data to the
208
    /// heap.
209
    #[must_use]
210
    pub fn into_owned(self) -> Value<'static> {
211
        match self {
212
            Value::Integer(value) => Value::Integer(value),
213
            Value::Float(value) => Value::Float(value),
214
            Value::Bool(value) => Value::Bool(value),
215
            Value::Char(value) => Value::Char(value),
216
            Value::Byte(value) => Value::Byte(value),
217
            Value::Identifier(value) => Value::Identifier(Cow::Owned(value.into_owned())),
218
            Value::String(value) => Value::String(Cow::Owned(value.into_owned())),
219
            Value::Bytes(value) => Value::Bytes(Cow::Owned(value.into_owned())),
220
            Value::Named(value) => Value::Named(value.into_owned()),
221
            Value::Tuple(value) => Value::Tuple(value.into_owned()),
222
            Value::Array(value) => Value::Array(value.into_owned()),
223
            Value::Map(value) => Value::Map(value.into_owned()),
224
        }
225
    }
226

            
227
    /// Returns this value as a floating point number.
228
    ///
229
    /// If this is an integer, this will cast the integer to an f64.
230
    #[must_use]
231
    pub fn as_f64(&self) -> Option<f64> {
232
        match self {
233
            Value::Integer(integer) => Some(integer.as_f64()),
234
            Value::Float(float) => Some(*float),
235
            _ => None,
236
        }
237
    }
238

            
239
    /// Returns this value as a str, if possible.
240
    ///
241
    /// `Identifier`, `String`, and `Bytes` bytes all can be returned from this
242
    /// function.
243
    #[must_use]
244
    pub fn as_str(&self) -> Option<&str> {
245
        match self {
246
            Value::Identifier(str) | Value::String(str) => Some(str),
247
            Value::Bytes(bytes) => str::from_utf8(bytes).ok(),
248
            _ => None,
249
        }
250
    }
251

            
252
    /// Returns the underlying bytes for this value, if it can be represented as
253
    /// a byte slice.
254
    ///
255
    /// `Identifier`, `String`, and `Bytes` bytes all can be returned from this
256
    /// function.
257
    #[must_use]
258
    pub fn as_bytes(&self) -> Option<&[u8]> {
259
        match self {
260
            Value::Identifier(str) | Value::String(str) => Some(str.as_bytes()),
261
            Value::Bytes(bytes) => Some(bytes),
262
            _ => None,
263
        }
264
    }
265
}
266

            
267
impl FromStr for Value<'static> {
268
    type Err = Error;
269

            
270
    fn from_str(s: &str) -> Result<Self, Self::Err> {
271
        Value::from_str(s, Config::default()).map(Value::into_owned)
272
    }
273
}
274

            
275
impl<'a> Display for Value<'a> {
276
2
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
277
2
        let mut writer = if f.alternate() {
278
1
            Writer::new(
279
1
                f,
280
1
                &writer::Config::Pretty {
281
1
                    indentation: Cow::Borrowed("  "),
282
1
                    newline: Cow::Borrowed("\n"),
283
1
                },
284
1
            )
285
        } else {
286
1
            Writer::new(f, &writer::Config::Compact)
287
        };
288
2
        writer.write_value(self)?;
289
2
        writer.finish();
290
2
        Ok(())
291
2
    }
292
}
293

            
294
/// A named structure.
295
#[derive(Debug, Clone, PartialEq)]
296
pub struct Named<'a> {
297
    /// The name of the structure.
298
    pub name: Cow<'a, str>,
299
    /// The contents of the structure.
300
    pub contents: StructContents<'a>,
301
}
302

            
303
impl<'a> Named<'a> {
304
    /// Returns an owned representation of this name, copying to the stack if
305
    /// needed.
306
    #[must_use]
307
    pub fn into_owned(self) -> Named<'static> {
308
        Named {
309
            name: Cow::Owned(self.name.into_owned()),
310
            contents: self.contents.into_owned(),
311
        }
312
    }
313
}
314

            
315
/// The contents of a structure.
316
#[derive(Debug, Clone, PartialEq)]
317
pub enum StructContents<'a> {
318
    /// Named fields, represented as a map.
319
    Map(Map<'a>),
320
    /// A tuple of valuees.
321
    Tuple(List<'a>),
322
}
323

            
324
impl<'a> StructContents<'a> {
325
    /// Returns an owned representation, copying to the heap if needed.
326
    #[must_use]
327
    pub fn into_owned(self) -> StructContents<'static> {
328
        match self {
329
            StructContents::Map(contents) => StructContents::Map(contents.into_owned()),
330
            StructContents::Tuple(contents) => StructContents::Tuple(contents.into_owned()),
331
        }
332
    }
333
}
334

            
335
/// A list of key-value pairs.
336
#[derive(Default, Debug, Clone, PartialEq)]
337
pub struct Map<'a>(pub Vec<(Value<'a>, Value<'a>)>);
338

            
339
impl<'a> Map<'a> {
340
    /// Returns an owned representation, copying to the heap if needed.
341
    #[must_use]
342
    pub fn into_owned(self) -> Map<'static> {
343
        Map(self
344
            .0
345
            .into_iter()
346
            .map(|(key, value)| (key.into_owned(), value.into_owned()))
347
            .collect())
348
    }
349
}
350

            
351
/// A list of values.
352
#[derive(Default, Debug, Clone, PartialEq)]
353
pub struct List<'a>(pub Vec<Value<'a>>);
354

            
355
impl<'a> List<'a> {
356
    /// Returns an empty list.
357
    #[must_use]
358
    pub const fn new() -> Self {
359
        Self(Vec::new())
360
    }
361

            
362
    /// Returns an owned representation, copying to the heap if needed.
363
    #[must_use]
364
    pub fn into_owned(self) -> List<'static> {
365
        List(self.0.into_iter().map(Value::into_owned).collect())
366
    }
367
}
368

            
369
#[cfg(feature = "serde")]
370
mod serde {
371
    use alloc::borrow::Cow;
372
    use alloc::string::{String, ToString};
373
    use alloc::{slice, vec};
374
    use core::fmt::Display;
375
    use core::num::TryFromIntError;
376
    use core::str::{self, Utf8Error};
377

            
378
    use serde::de::{EnumAccess, MapAccess, SeqAccess, VariantAccess};
379
    use serde::ser::{
380
        SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
381
        SerializeTupleStruct, SerializeTupleVariant,
382
    };
383
    use serde::{Deserializer, Serializer};
384

            
385
    use super::{List, StructContents};
386
    use crate::parser::Nested;
387
    use crate::tokenizer::Integer;
388
    use crate::value::{Map, Named, OwnedValue, Value};
389

            
390
    pub struct ValueSerializer;
391

            
392
    impl Serializer for ValueSerializer {
393
        type Error = ToValueError;
394
        type Ok = OwnedValue;
395
        type SerializeMap = MapSerializer;
396
        type SerializeSeq = SequenceSerializer;
397
        type SerializeStruct = MapSerializer;
398
        type SerializeStructVariant = MapSerializer;
399
        type SerializeTuple = SequenceSerializer;
400
        type SerializeTupleStruct = SequenceSerializer;
401
        type SerializeTupleVariant = SequenceSerializer;
402

            
403
1
        fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
404
1
            Ok(Value::Bool(v))
405
1
        }
406

            
407
1
        fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
408
1
            Ok(Value::Integer(Integer::from(v)))
409
1
        }
410

            
411
1
        fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
412
1
            Ok(Value::Integer(Integer::from(v)))
413
1
        }
414

            
415
1
        fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
416
1
            Ok(Value::Integer(Integer::from(v)))
417
1
        }
418

            
419
2
        fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
420
2
            Ok(Value::Integer(Integer::from(v)))
421
2
        }
422

            
423
1
        fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
424
1
            Ok(Value::Integer(Integer::from(v)))
425
1
        }
426

            
427
1
        fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
428
1
            Ok(Value::Integer(Integer::from(v)))
429
1
        }
430

            
431
1
        fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
432
1
            Ok(Value::Integer(Integer::from(v)))
433
1
        }
434

            
435
2
        fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
436
2
            Ok(Value::Integer(Integer::from(v)))
437
2
        }
438

            
439
        fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
440
            Ok(Value::Float(f64::from(v)))
441
        }
442

            
443
        fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
444
            Ok(Value::Float(v))
445
        }
446

            
447
1
        fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
448
1
            Ok(Value::Char(v))
449
1
        }
450

            
451
17
        fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
452
17
            Ok(Value::String(Cow::Owned(v.to_string())))
453
17
        }
454

            
455
1
        fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
456
1
            Ok(Value::Bytes(Cow::Owned(v.to_vec())))
457
1
        }
458

            
459
        fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
460
            Ok(Value::Identifier(Cow::Borrowed("None")))
461
        }
462

            
463
        fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
464
        where
465
            T: serde::Serialize + ?Sized,
466
        {
467
            Ok(Value::Named(Named {
468
                name: Cow::Borrowed("Some"),
469
                contents: StructContents::Tuple(List(vec![value.serialize(ValueSerializer)?])),
470
            }))
471
        }
472

            
473
        fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
474
            Ok(Value::Tuple(List::default()))
475
        }
476

            
477
        fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
478
            Ok(Value::Identifier(Cow::Owned(name.to_string())))
479
        }
480

            
481
        fn serialize_unit_variant(
482
            self,
483
            _name: &'static str,
484
            _variant_index: u32,
485
            variant: &'static str,
486
        ) -> Result<Self::Ok, Self::Error> {
487
            Ok(Value::Identifier(Cow::Owned(variant.to_string())))
488
        }
489

            
490
        fn serialize_newtype_struct<T>(
491
            self,
492
            name: &'static str,
493
            value: &T,
494
        ) -> Result<Self::Ok, Self::Error>
495
        where
496
            T: serde::Serialize + ?Sized,
497
        {
498
            Ok(Value::Named(Named {
499
                name: Cow::Owned(name.to_string()),
500
                contents: StructContents::Tuple(List(vec![value.serialize(ValueSerializer)?])),
501
            }))
502
        }
503

            
504
        fn serialize_newtype_variant<T>(
505
            self,
506
            _name: &'static str,
507
            _variant_index: u32,
508
            variant: &'static str,
509
            value: &T,
510
        ) -> Result<Self::Ok, Self::Error>
511
        where
512
            T: serde::Serialize + ?Sized,
513
        {
514
            Ok(Value::Named(Named {
515
                name: Cow::Owned(variant.to_string()),
516
                contents: StructContents::Tuple(List(vec![value.serialize(ValueSerializer)?])),
517
            }))
518
        }
519

            
520
        fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
521
            Ok(SequenceSerializer::new(None, Nested::List))
522
        }
523

            
524
        fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
525
            Ok(SequenceSerializer::new(None, Nested::Tuple))
526
        }
527

            
528
        fn serialize_tuple_struct(
529
            self,
530
            name: &'static str,
531
            _len: usize,
532
        ) -> Result<Self::SerializeTupleStruct, Self::Error> {
533
            Ok(SequenceSerializer::new(
534
                Some(name.to_string()),
535
                Nested::Tuple,
536
            ))
537
        }
538

            
539
        fn serialize_tuple_variant(
540
            self,
541
            _name: &'static str,
542
            _variant_index: u32,
543
            variant: &'static str,
544
            _len: usize,
545
        ) -> Result<Self::SerializeTupleVariant, Self::Error> {
546
            Ok(SequenceSerializer::new(
547
                Some(variant.to_string()),
548
                Nested::Tuple,
549
            ))
550
        }
551

            
552
        fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
553
            Ok(MapSerializer {
554
                name: None,
555
                contents: Map::default(),
556
            })
557
        }
558

            
559
1
        fn serialize_struct(
560
1
            self,
561
1
            name: &'static str,
562
1
            _len: usize,
563
1
        ) -> Result<Self::SerializeStruct, Self::Error> {
564
1
            Ok(MapSerializer {
565
1
                name: Some(name.to_string()),
566
1
                contents: Map::default(),
567
1
            })
568
1
        }
569

            
570
        fn serialize_struct_variant(
571
            self,
572
            _name: &'static str,
573
            _variant_index: u32,
574
            variant: &'static str,
575
            _len: usize,
576
        ) -> Result<Self::SerializeStructVariant, Self::Error> {
577
            Ok(MapSerializer {
578
                name: Some(variant.to_string()),
579
                contents: Map::default(),
580
            })
581
        }
582

            
583
1
        fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
584
1
            Ok(Value::Integer(Integer::try_from(v)?))
585
1
        }
586

            
587
1
        fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
588
1
            Ok(Value::Integer(Integer::try_from(v)?))
589
1
        }
590
    }
591

            
592
    pub struct SequenceSerializer {
593
        name: Option<String>,
594
        kind: Nested,
595
        contents: List<'static>,
596
    }
597

            
598
    impl SequenceSerializer {
599
        pub fn new(name: Option<String>, kind: Nested) -> Self {
600
            Self {
601
                name,
602
                kind,
603
                contents: List::default(),
604
            }
605
        }
606
    }
607

            
608
    impl SerializeSeq for SequenceSerializer {
609
        type Error = ToValueError;
610
        type Ok = OwnedValue;
611

            
612
        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
613
        where
614
            T: serde::Serialize + ?Sized,
615
        {
616
            self.contents.0.push(value.serialize(ValueSerializer)?);
617
            Ok(())
618
        }
619

            
620
        fn end(self) -> Result<Self::Ok, Self::Error> {
621
            match (self.name, self.kind) {
622
                (Some(name), Nested::List | Nested::Tuple) => Ok(Value::Named(Named {
623
                    name: Cow::Owned(name),
624
                    contents: StructContents::Tuple(self.contents),
625
                })),
626
                (None, Nested::List) => Ok(Value::Array(self.contents)),
627
                (None, Nested::Tuple) => Ok(Value::Tuple(self.contents)),
628
                (_, Nested::Map) => unreachable!(),
629
            }
630
        }
631
    }
632

            
633
    impl SerializeTuple for SequenceSerializer {
634
        type Error = ToValueError;
635
        type Ok = OwnedValue;
636

            
637
        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
638
        where
639
            T: serde::Serialize + ?Sized,
640
        {
641
            SerializeSeq::serialize_element(self, value)
642
        }
643

            
644
        fn end(self) -> Result<Self::Ok, Self::Error> {
645
            SerializeSeq::end(self)
646
        }
647
    }
648

            
649
    impl SerializeTupleStruct for SequenceSerializer {
650
        type Error = ToValueError;
651
        type Ok = OwnedValue;
652

            
653
        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
654
        where
655
            T: serde::Serialize + ?Sized,
656
        {
657
            SerializeSeq::serialize_element(self, value)
658
        }
659

            
660
        fn end(self) -> Result<Self::Ok, Self::Error> {
661
            SerializeSeq::end(self)
662
        }
663
    }
664

            
665
    impl SerializeTupleVariant for SequenceSerializer {
666
        type Error = ToValueError;
667
        type Ok = OwnedValue;
668

            
669
        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
670
        where
671
            T: serde::Serialize + ?Sized,
672
        {
673
            SerializeSeq::serialize_element(self, value)
674
        }
675

            
676
        fn end(self) -> Result<Self::Ok, Self::Error> {
677
            SerializeSeq::end(self)
678
        }
679
    }
680

            
681
    #[derive(Default)]
682
    pub struct MapSerializer {
683
        name: Option<String>,
684
        contents: Map<'static>,
685
    }
686

            
687
    impl SerializeMap for MapSerializer {
688
        type Error = ToValueError;
689
        type Ok = OwnedValue;
690

            
691
16
        fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
692
16
        where
693
16
            T: serde::Serialize + ?Sized,
694
16
        {
695
16
            self.contents.0.push((
696
16
                key.serialize(ValueSerializer)?,
697
16
                Value::Tuple(List::default()),
698
16
            ));
699
16
            Ok(())
700
16
        }
701

            
702
16
        fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
703
16
        where
704
16
            T: serde::Serialize + ?Sized,
705
16
        {
706
16
            self.contents
707
16
                .0
708
16
                .last_mut()
709
16
                .expect("serialize_key not called")
710
16
                .1 = value.serialize(ValueSerializer)?;
711
16
            Ok(())
712
16
        }
713

            
714
1
        fn end(self) -> Result<Self::Ok, Self::Error> {
715
1
            if let Some(name) = self.name {
716
1
                Ok(Value::Named(Named {
717
1
                    name: Cow::Owned(name),
718
1
                    contents: StructContents::Map(self.contents),
719
1
                }))
720
            } else {
721
                Ok(Value::Map(self.contents))
722
            }
723
1
        }
724
    }
725

            
726
    impl SerializeStruct for MapSerializer {
727
        type Error = ToValueError;
728
        type Ok = OwnedValue;
729

            
730
16
        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
731
16
        where
732
16
            T: serde::Serialize + ?Sized,
733
16
        {
734
16
            SerializeMap::serialize_key(self, key)?;
735
16
            SerializeMap::serialize_value(self, value)
736
16
        }
737

            
738
1
        fn end(self) -> Result<Self::Ok, Self::Error> {
739
1
            SerializeMap::end(self)
740
1
        }
741
    }
742

            
743
    impl SerializeStructVariant for MapSerializer {
744
        type Error = ToValueError;
745
        type Ok = OwnedValue;
746

            
747
        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
748
        where
749
            T: serde::Serialize + ?Sized,
750
        {
751
            SerializeMap::serialize_key(self, key)?;
752
            SerializeMap::serialize_value(self, value)
753
        }
754

            
755
        fn end(self) -> Result<Self::Ok, Self::Error> {
756
            SerializeMap::end(self)
757
        }
758
    }
759

            
760
    #[derive(Clone)]
761
    pub struct ValueDeserializer<'a, 'de>(pub &'a Value<'de>);
762

            
763
    macro_rules! deserialize_int {
764
        ($deserialize_name:ident, $as_name:ident, $visit_name:ident, $expected:expr) => {
765
12
            fn $deserialize_name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
766
12
            where
767
12
                V: serde::de::Visitor<'de>,
768
12
            {
769
12
                if let Some(value) = self.0.$as_name() {
770
12
                    visitor.$visit_name(value)
771
                } else {
772
                    Err(FromValueError::Expected($expected))
773
                }
774
12
            }
775
        };
776
    }
777

            
778
    impl<'a, 'de> Deserializer<'de> for ValueDeserializer<'a, 'de> {
779
        type Error = FromValueError;
780

            
781
        deserialize_int!(deserialize_i8, as_i8, visit_i8, ExpectedKind::I8);
782

            
783
        deserialize_int!(deserialize_i16, as_i16, visit_i16, ExpectedKind::I16);
784

            
785
        deserialize_int!(deserialize_i32, as_i32, visit_i32, ExpectedKind::I32);
786

            
787
        deserialize_int!(deserialize_i64, as_i64, visit_i64, ExpectedKind::I64);
788

            
789
        deserialize_int!(deserialize_i128, as_i128, visit_i128, ExpectedKind::I128);
790

            
791
        deserialize_int!(deserialize_u8, as_u8, visit_u8, ExpectedKind::U8);
792

            
793
        deserialize_int!(deserialize_u16, as_u16, visit_u16, ExpectedKind::U16);
794

            
795
        deserialize_int!(deserialize_u32, as_u32, visit_u32, ExpectedKind::U32);
796

            
797
        deserialize_int!(deserialize_u64, as_u64, visit_u64, ExpectedKind::U64);
798

            
799
        deserialize_int!(deserialize_u128, as_u128, visit_u128, ExpectedKind::U128);
800

            
801
        deserialize_int!(deserialize_f64, as_f64, visit_f64, ExpectedKind::Float);
802

            
803
        #[allow(clippy::cast_possible_truncation)]
804
        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
805
        where
806
            V: serde::de::Visitor<'de>,
807
        {
808
            match &self.0 {
809
                Value::Integer(value) => match *value {
810
                    Integer::Usize(usize) => match usize::BITS {
811
                        0..=16 => visitor.visit_u16(usize as u16),
812
                        17..=32 => visitor.visit_u32(usize as u32),
813
                        33..=64 => visitor.visit_u64(usize as u64),
814
                        65..=128 => visitor.visit_u128(usize as u128),
815
                        _ => unreachable!("unsupported pointer width"),
816
                    },
817
                    Integer::Isize(isize) => match usize::BITS {
818
                        0..=16 => visitor.visit_i16(isize as i16),
819
                        17..=32 => visitor.visit_i32(isize as i32),
820
                        33..=64 => visitor.visit_i64(isize as i64),
821
                        65..=128 => visitor.visit_i128(isize as i128),
822
                        _ => unreachable!("unsupported pointer width"),
823
                    },
824
                    #[cfg(feature = "integer128")]
825
                    Integer::UnsignedLarge(large) => visitor.visit_u128(large),
826
                    #[cfg(not(feature = "integer128"))]
827
                    Integer::UnsignedLarge(large) => visitor.visit_u64(large),
828
                    #[cfg(feature = "integer128")]
829
                    Integer::SignedLarge(large) => visitor.visit_i128(large),
830
                    #[cfg(not(feature = "integer128"))]
831
                    Integer::SignedLarge(large) => visitor.visit_i64(large),
832
                },
833
                Value::Float(value) => visitor.visit_f64(*value),
834
                Value::Bool(value) => visitor.visit_bool(*value),
835
                Value::Char(value) => visitor.visit_char(*value),
836
                Value::Byte(value) => visitor.visit_u8(*value),
837
                Value::Identifier(value) => match value {
838
                    Cow::Borrowed(str) => visitor.visit_borrowed_str(str),
839
                    Cow::Owned(str) => visitor.visit_str(str),
840
                },
841
                Value::String(value) => visitor.visit_str(value),
842
                Value::Bytes(value) => match value {
843
                    Cow::Borrowed(bytes) => visitor.visit_borrowed_bytes(bytes),
844
                    Cow::Owned(bytes) => visitor.visit_bytes(bytes),
845
                },
846
                Value::Named(value) => match &value.contents {
847
                    StructContents::Map(map) => visitor.visit_map(MapDeserializer::new(map)),
848
                    StructContents::Tuple(list) => {
849
                        visitor.visit_seq(SequenceDeserializer(list.0.iter()))
850
                    }
851
                },
852
                Value::Array(list) | Value::Tuple(list) => {
853
                    visitor.visit_seq(SequenceDeserializer(list.0.iter()))
854
                }
855
                Value::Map(map) => visitor.visit_map(MapDeserializer::new(map)),
856
            }
857
        }
858

            
859
1
        fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
860
1
        where
861
1
            V: serde::de::Visitor<'de>,
862
1
        {
863
1
            match &self.0 {
864
                Value::Integer(int) => visitor.visit_bool(!int.is_zero()),
865
1
                Value::Bool(bool) => visitor.visit_bool(*bool),
866
                _ => Err(FromValueError::Expected(ExpectedKind::Bool)),
867
            }
868
1
        }
869

            
870
        #[allow(clippy::cast_possible_truncation)]
871
        fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
872
        where
873
            V: serde::de::Visitor<'de>,
874
        {
875
            if let Some(value) = self.0.as_f64() {
876
                visitor.visit_f32(value as f32)
877
            } else {
878
                Err(FromValueError::Expected(ExpectedKind::Float))
879
            }
880
        }
881

            
882
1
        fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
883
1
        where
884
1
            V: serde::de::Visitor<'de>,
885
1
        {
886
1
            if let Value::Char(ch) = &self.0 {
887
1
                visitor.visit_char(*ch)
888
            } else {
889
                Err(FromValueError::Expected(ExpectedKind::Char))
890
            }
891
1
        }
892

            
893
17
        fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
894
17
        where
895
17
            V: serde::de::Visitor<'de>,
896
17
        {
897
17
            match &self.0 {
898
17
                Value::String(str) | Value::Identifier(str) => match str {
899
                    Cow::Borrowed(str) => visitor.visit_borrowed_str(str),
900
17
                    Cow::Owned(str) => visitor.visit_str(str),
901
                },
902
                Value::Bytes(bytes) => match bytes {
903
                    Cow::Borrowed(bytes) => {
904
                        let str = str::from_utf8(bytes)?;
905
                        visitor.visit_borrowed_str(str)
906
                    }
907
                    Cow::Owned(bytes) => {
908
                        let str = str::from_utf8(bytes)?;
909
                        visitor.visit_str(str)
910
                    }
911
                },
912
                Value::Named(name) => match &name.name {
913
                    Cow::Borrowed(str) => visitor.visit_borrowed_str(str),
914
                    Cow::Owned(str) => visitor.visit_str(str),
915
                },
916
                _ => Err(FromValueError::Expected(ExpectedKind::String)),
917
            }
918
17
        }
919

            
920
1
        fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
921
1
        where
922
1
            V: serde::de::Visitor<'de>,
923
1
        {
924
1
            self.deserialize_str(visitor)
925
1
        }
926

            
927
1
        fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
928
1
        where
929
1
            V: serde::de::Visitor<'de>,
930
1
        {
931
1
            match &self.0 {
932
1
                Value::Bytes(bytes) => match bytes {
933
                    Cow::Borrowed(bytes) => visitor.visit_borrowed_bytes(bytes),
934
1
                    Cow::Owned(bytes) => visitor.visit_bytes(bytes),
935
                },
936
                Value::String(str) | Value::Identifier(str) => match str {
937
                    Cow::Borrowed(str) => visitor.visit_borrowed_bytes(str.as_bytes()),
938
                    Cow::Owned(str) => visitor.visit_bytes(str.as_bytes()),
939
                },
940
                _ => Err(FromValueError::Expected(ExpectedKind::Bytes)),
941
            }
942
1
        }
943

            
944
1
        fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
945
1
        where
946
1
            V: serde::de::Visitor<'de>,
947
1
        {
948
1
            self.deserialize_bytes(visitor)
949
1
        }
950

            
951
        fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
952
        where
953
            V: serde::de::Visitor<'de>,
954
        {
955
            match &self.0 {
956
                Value::String(name) | Value::Identifier(name) if name == "None" => {
957
                    visitor.visit_none()
958
                }
959
                Value::Named(Named {
960
                    name,
961
                    contents: StructContents::Tuple(list),
962
                }) if name == "Some" && !list.0.is_empty() => {
963
                    visitor.visit_some(ValueDeserializer(list.0.first().expect("length checked")))
964
                }
965
                // To support changing a T to Option<T>, we can fuzzily allow a
966
                // value to be treated as Some(). TODO should this be optional?
967
                _ => visitor.visit_some(self),
968
            }
969
        }
970

            
971
        fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
972
        where
973
            V: serde::de::Visitor<'de>,
974
        {
975
            match &self.0 {
976
                Value::Named(Named {
977
                    contents: StructContents::Tuple(_),
978
                    ..
979
                })
980
                | Value::Tuple(_)
981
                | Value::Array(_) => visitor.visit_unit(),
982
                _ => Err(FromValueError::Expected(ExpectedKind::Unit)),
983
            }
984
        }
985

            
986
        fn deserialize_unit_struct<V>(
987
            self,
988
            _name: &'static str,
989
            visitor: V,
990
        ) -> Result<V::Value, Self::Error>
991
        where
992
            V: serde::de::Visitor<'de>,
993
        {
994
            self.deserialize_unit(visitor)
995
        }
996

            
997
        fn deserialize_newtype_struct<V>(
998
            self,
999
            name: &'static str,
            visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            match &self.0 {
                Value::Named(named) if named.name == name => match &named.contents {
                    StructContents::Tuple(contents) => {
                        if let Some(first) = contents.0.first() {
                            visitor.visit_newtype_struct(ValueDeserializer(first))
                        } else {
                            visitor.visit_newtype_struct(ValueDeserializer(&Value::unit()))
                        }
                    }
                    StructContents::Map(map) => {
                        if let Some((_, first)) = map.0.first() {
                            visitor.visit_newtype_struct(ValueDeserializer(first))
                        } else {
                            visitor.visit_newtype_struct(ValueDeserializer(&Value::unit()))
                        }
                    }
                },
                _ => visitor.visit_newtype_struct(self),
            }
        }

            
        fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            match &self.0 {
                Value::Named(Named {
                    contents: StructContents::Tuple(list),
                    ..
                })
                | Value::Tuple(list)
                | Value::Array(list) => visitor.visit_seq(SequenceDeserializer(list.0.iter())),
                _ => Err(FromValueError::Expected(ExpectedKind::Sequence)),
            }
        }

            
        fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            self.deserialize_seq(visitor)
        }

            
        fn deserialize_tuple_struct<V>(
            self,
            _name: &'static str,
            len: usize,
            visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            self.deserialize_tuple(len, visitor)
        }

            
1
        fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1
        where
1
            V: serde::de::Visitor<'de>,
1
        {
1
            match &self.0 {
                Value::Named(Named {
1
                    contents: StructContents::Map(map),
                    ..
                })
1
                | Value::Map(map) => visitor.visit_map(MapDeserializer::new(map)),
                _ => Err(FromValueError::Expected(ExpectedKind::Map)),
            }
1
        }

            
1
        fn deserialize_struct<V>(
1
            self,
1
            _name: &'static str,
1
            _fields: &'static [&'static str],
1
            visitor: V,
1
        ) -> Result<V::Value, Self::Error>
1
        where
1
            V: serde::de::Visitor<'de>,
1
        {
1
            self.deserialize_map(visitor)
1
        }

            
        fn deserialize_enum<V>(
            self,
            _name: &'static str,
            _variants: &'static [&'static str],
            visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            visitor.visit_enum(self)
        }

            
16
        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
16
        where
16
            V: serde::de::Visitor<'de>,
16
        {
16
            self.deserialize_str(visitor)
16
        }

            
        fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            self.deserialize_any(visitor)
        }
    }

            
    impl<'a, 'de> EnumAccess<'de> for ValueDeserializer<'a, 'de> {
        type Error = FromValueError;
        type Variant = EnumVariantAccessor<'a, 'de>;

            
        fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
        where
            V: serde::de::DeserializeSeed<'de>,
        {
            match &self.0 {
                Value::Identifier(_) | Value::String(_) => {
                    Ok((seed.deserialize(self)?, EnumVariantAccessor::Unit))
                }
                Value::Named(named) => {
                    let variant =
                        seed.deserialize(ValueDeserializer(&Value::String(named.name.clone())))?;

            
                    let accessor = match &named.contents {
                        StructContents::Map(map) => EnumVariantAccessor::Map(map),
                        StructContents::Tuple(list) => EnumVariantAccessor::Tuple(list),
                    };

            
                    Ok((variant, accessor))
                }
                _ => Err(FromValueError::Expected(ExpectedKind::Enum)),
            }
        }
    }

            
    pub enum EnumVariantAccessor<'a, 'de> {
        Unit,
        Tuple(&'a List<'de>),
        Map(&'a Map<'de>),
    }

            
    impl<'a, 'de> VariantAccess<'de> for EnumVariantAccessor<'a, 'de> {
        type Error = FromValueError;

            
        fn unit_variant(self) -> Result<(), Self::Error> {
            Ok(())
        }

            
        fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
        where
            T: serde::de::DeserializeSeed<'de>,
        {
            match self {
                EnumVariantAccessor::Unit => seed.deserialize(ValueDeserializer(&Value::unit())),
                EnumVariantAccessor::Tuple(list) => {
                    if let Some(first) = list.0.first() {
                        seed.deserialize(ValueDeserializer(first))
                    } else {
                        seed.deserialize(ValueDeserializer(&Value::unit()))
                    }
                }
                EnumVariantAccessor::Map(_) => Err(FromValueError::Expected(ExpectedKind::Newtype)),
            }
        }

            
        fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            match self {
                EnumVariantAccessor::Unit => visitor.visit_seq(SequenceDeserializer([].iter())),
                EnumVariantAccessor::Tuple(list) => {
                    visitor.visit_seq(SequenceDeserializer(list.0.iter()))
                }
                EnumVariantAccessor::Map(map) => visitor.visit_map(MapDeserializer::new(map)),
            }
        }

            
        fn struct_variant<V>(
            self,
            _fields: &'static [&'static str],
            visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            match self {
                EnumVariantAccessor::Unit => visitor.visit_seq(SequenceDeserializer([].iter())),
                EnumVariantAccessor::Tuple(list) => {
                    visitor.visit_seq(SequenceDeserializer(list.0.iter()))
                }
                EnumVariantAccessor::Map(map) => visitor.visit_map(MapDeserializer::new(map)),
            }
        }
    }

            
    pub struct MapDeserializer<'a, 'de> {
        map: &'a Map<'de>,
        index: usize,
    }

            
    impl<'a, 'de> MapDeserializer<'a, 'de> {
1
        pub fn new(map: &'a Map<'de>) -> Self {
1
            Self { map, index: 0 }
1
        }
    }

            
    impl<'a, 'de> MapAccess<'de> for MapDeserializer<'a, 'de> {
        type Error = FromValueError;

            
17
        fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
17
        where
17
            K: serde::de::DeserializeSeed<'de>,
17
        {
17
            self.map
17
                .0
17
                .get(self.index)
17
                .map(|item| seed.deserialize(ValueDeserializer(&item.0)))
17
                .transpose()
17
        }

            
16
        fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
16
        where
16
            V: serde::de::DeserializeSeed<'de>,
16
        {
16
            let value = seed.deserialize(ValueDeserializer(&self.map.0[self.index].1))?;
16
            self.index += 1;
16
            Ok(value)
16
        }
    }

            
    pub struct SequenceDeserializer<'a, 'de>(slice::Iter<'a, Value<'de>>);

            
    impl<'a, 'de> SeqAccess<'de> for SequenceDeserializer<'a, 'de> {
        type Error = FromValueError;

            
        fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
        where
            T: serde::de::DeserializeSeed<'de>,
        {
            self.0
                .next()
                .map(|item| seed.deserialize(ValueDeserializer(item)))
                .transpose()
        }
    }

            
    /// An error from serializing to a [`Value`].
    #[derive(Debug, PartialEq)]

            
    pub enum ToValueError {
        /// A custom serialization error.
        Message(String),
        /// An integer was too larget to represent.
        IntegerTooLarge(TryFromIntError),
    }

            
    impl From<TryFromIntError> for ToValueError {
        fn from(value: TryFromIntError) -> Self {
            Self::IntegerTooLarge(value)
        }
    }

            
    impl serde::ser::Error for ToValueError {
        fn custom<T>(msg: T) -> Self
        where
            T: Display,
        {
            Self::Message(msg.to_string())
        }
    }

            
    impl serde::ser::StdError for ToValueError {}

            
    impl Display for ToValueError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                ToValueError::Message(message) => f.write_str(message),
                ToValueError::IntegerTooLarge(err) => write!(f, "{err}"),
            }
        }
    }

            
    /// An error from deserializing from a [`Value`].
    #[derive(Debug, PartialEq)]

            
    pub enum FromValueError {
        /// A custom serialization error.
        Message(String),
        /// Expected a kind of data, but encountered another kind.
        Expected(ExpectedKind),
        /// Invalid UTF-8 was encountered.
        InvalidUtf8,
    }

            
    impl serde::de::Error for FromValueError {
        fn custom<T>(msg: T) -> Self
        where
            T: Display,
        {
            Self::Message(msg.to_string())
        }
    }

            
    impl From<Utf8Error> for FromValueError {
        fn from(_value: Utf8Error) -> Self {
            Self::InvalidUtf8
        }
    }

            
    impl serde::de::StdError for FromValueError {}

            
    impl Display for FromValueError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                FromValueError::Message(message) => f.write_str(message),
                FromValueError::Expected(kind) => write!(f, "expected {kind}"),
                FromValueError::InvalidUtf8 => {
                    f.write_str("invalid utf8 when interpreting bytes as a string")
                }
            }
        }
    }

            
    #[derive(Debug, PartialEq)]
    pub enum ExpectedKind {
        I8,
        I16,
        I32,
        I64,
        I128,
        U8,
        U16,
        U32,
        U64,
        U128,
        Bool,
        Char,
        String,
        Bytes,
        Float,
        Enum,
        Map,
        Sequence,
        Unit,
        Newtype,
    }

            
    impl Display for ExpectedKind {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                ExpectedKind::I8 => f.write_str("i8"),
                ExpectedKind::I16 => f.write_str("i16"),
                ExpectedKind::I32 => f.write_str("i32"),
                ExpectedKind::I64 => f.write_str("i64"),
                ExpectedKind::I128 => f.write_str("i128"),
                ExpectedKind::U8 => f.write_str("u8"),
                ExpectedKind::U16 => f.write_str("u16"),
                ExpectedKind::U32 => f.write_str("u32"),
                ExpectedKind::U64 => f.write_str("u64"),
                ExpectedKind::U128 => f.write_str("u128"),
                ExpectedKind::Bool => f.write_str("bool"),
                ExpectedKind::Char => f.write_str("char"),
                ExpectedKind::String => f.write_str("String"),
                ExpectedKind::Bytes => f.write_str("Bytes"),
                ExpectedKind::Float => f.write_str("Float"),
                ExpectedKind::Enum => f.write_str("Enum"),
                ExpectedKind::Map => f.write_str("Map"),
                ExpectedKind::Sequence => f.write_str("Sequence"),
                ExpectedKind::Unit => f.write_str("()"),
                ExpectedKind::Newtype => f.write_str("Newtype"),
            }
        }
    }
}

            
#[test]
1
fn display() {
    use alloc::string::ToString;
    use alloc::{format, vec};

            
1
    assert_eq!(
1
        Value::Named(Named {
1
            name: Cow::Borrowed("Hello"),
1
            contents: StructContents::Tuple(List(vec![Value::String(Cow::Borrowed("World"))]))
1
        })
1
        .to_string(),
1
        "Hello(\"World\")"
1
    );

            
1
    assert_eq!(
1
        format!(
1
            "{:#}",
1
            Value::Named(Named {
1
                name: Cow::Borrowed("Hello"),
1
                contents: StructContents::Tuple(List(vec![Value::String(Cow::Borrowed("World"))]))
1
            })
1
        ),
1
        "Hello(\n  \"World\"\n)"
1
    );
1
}

            
#[cfg(feature = "serde")]
pub use self::serde::{FromValueError, ToValueError};