serde_hjson/
value.rs

1//! Hjson Value
2//!
3//! This module is centered around the `Value` type, which can represent all possible Hjson values.
4//!
5//! # Example of use:
6//!
7//! ```rust
8//! extern crate serde_hjson;
9//!
10//! use serde_hjson::Value;
11//!
12//! fn main() {
13//!     let s = "{x: 1.0, y: 2.0}";
14//!     let value: Value = serde_hjson::from_str(s).unwrap();
15//! }
16//! ```
17//!
18//! It is also possible to deserialize from a `Value` type:
19//!
20//! ```rust
21//! extern crate serde_hjson;
22//!
23//! use serde_hjson::{Value, Map};
24//!
25//! fn main() {
26//!     let mut map = Map::new();
27//!     map.insert(String::from("x"), Value::F64(1.0));
28//!     map.insert(String::from("y"), Value::F64(2.0));
29//!     let value = Value::Object(map);
30//!
31//!     let map: Map<String, f64> = serde_hjson::from_value(value).unwrap();
32//! }
33//! ```
34
35#[cfg(not(feature = "preserve_order"))]
36use std::collections::{btree_map, BTreeMap};
37
38#[cfg(feature = "preserve_order")]
39use linked_hash_map::{self, LinkedHashMap};
40
41use std::fmt;
42use std::io;
43use std::str;
44use std::vec;
45
46use num_traits::NumCast;
47
48use serde::{de, ser};
49
50use super::error::{Error, ErrorCode};
51
52type Result<T, E = Error> = std::result::Result<T, E>;
53
54/// Represents a key/value type.
55#[cfg(not(feature = "preserve_order"))]
56pub type Map<K, V> = BTreeMap<K, V>;
57/// Represents a key/value type.
58#[cfg(feature = "preserve_order")]
59pub type Map<K, V> = LinkedHashMap<K, V>;
60
61/// Represents the `IntoIter` type.
62#[cfg(not(feature = "preserve_order"))]
63pub type MapIntoIter<K, V> = btree_map::IntoIter<K, V>;
64/// Represents the IntoIter type.
65#[cfg(feature = "preserve_order")]
66pub type MapIntoIter<K, V> = linked_hash_map::IntoIter<K, V>;
67
68fn map_with_capacity<K: std::hash::Hash + Eq, V>(size: Option<usize>) -> Map<K, V> {
69    #[cfg(not(feature = "preserve_order"))]
70    {
71        let _ = size;
72        BTreeMap::new()
73    }
74
75    #[cfg(feature = "preserve_order")]
76    {
77        LinkedHashMap::with_capacity(size.unwrap_or(0))
78    }
79}
80
81/// Represents a Hjson/JSON value
82#[derive(Clone, PartialEq)]
83pub enum Value {
84    /// Represents a JSON null value
85    Null,
86
87    /// Represents a JSON Boolean
88    Bool(bool),
89
90    /// Represents a JSON signed integer
91    I64(i64),
92
93    /// Represents a JSON unsigned integer
94    U64(u64),
95
96    /// Represents a JSON floating point number
97    F64(f64),
98
99    /// Represents a JSON string
100    String(String),
101
102    /// Represents a JSON array
103    Array(Vec<Value>),
104
105    /// Represents a JSON object
106    Object(Map<String, Value>),
107}
108
109impl Value {
110    /// If the `Value` is an Object, returns the value associated with the provided key.
111    /// Otherwise, returns None.
112    pub fn find<'a>(&'a self, key: &str) -> Option<&'a Value> {
113        match *self {
114            Value::Object(ref map) => map.get(key),
115            _ => None,
116        }
117    }
118
119    /// Attempts to get a nested Value Object for each key in `keys`.
120    /// If any key is found not to exist, find_path will return None.
121    /// Otherwise, it will return the `Value` associated with the final key.
122    pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value> {
123        let mut target = self;
124        for key in keys {
125            match target.find(key) {
126                Some(t) => {
127                    target = t;
128                }
129                None => return None,
130            }
131        }
132        Some(target)
133    }
134
135    /// Looks up a value by a JSON Pointer.
136    ///
137    /// JSON Pointer defines a string syntax for identifying a specific value
138    /// within a JavaScript Object Notation (JSON) document.
139    ///
140    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
141    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
142    /// addressed value is returned and if there is no such value `None` is
143    /// returned.
144    ///
145    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
146    pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> {
147        fn parse_index(s: &str) -> Option<usize> {
148            if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
149                return None;
150            }
151            s.parse().ok()
152        }
153        if pointer.is_empty() {
154            return Some(self);
155        }
156        if !pointer.starts_with('/') {
157            return None;
158        }
159        let mut target = self;
160        for escaped_token in pointer.split('/').skip(1) {
161            let token = escaped_token.replace("~1", "/").replace("~0", "~");
162            let target_opt = match *target {
163                Value::Object(ref map) => map.get(&token[..]),
164                Value::Array(ref list) => parse_index(&token[..]).and_then(|x| list.get(x)),
165                _ => return None,
166            };
167            if let Some(t) = target_opt {
168                target = t;
169            } else {
170                return None;
171            }
172        }
173        Some(target)
174    }
175
176    /// If the `Value` is an Object, performs a depth-first search until
177    /// a value associated with the provided key is found. If no value is found
178    /// or the `Value` is not an Object, returns None.
179    pub fn search<'a>(&'a self, key: &str) -> Option<&'a Value> {
180        match *self {
181            Value::Object(ref map) => match map.get(key) {
182                Some(json_value) => Some(json_value),
183                None => {
184                    for v in map.values() {
185                        match v.search(key) {
186                            x if x.is_some() => return x,
187                            _ => (),
188                        }
189                    }
190                    None
191                }
192            },
193            _ => None,
194        }
195    }
196
197    /// Returns true if the `Value` is an Object. Returns false otherwise.
198    pub fn is_object(&self) -> bool {
199        self.as_object().is_some()
200    }
201
202    /// If the `Value` is an Object, returns the associated Map.
203    /// Returns None otherwise.
204    pub fn as_object(&self) -> Option<&Map<String, Value>> {
205        match *self {
206            Value::Object(ref map) => Some(map),
207            _ => None,
208        }
209    }
210
211    /// If the `Value` is an Object, returns the associated mutable Map.
212    /// Returns None otherwise.
213    pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> {
214        match *self {
215            Value::Object(ref mut map) => Some(map),
216            _ => None,
217        }
218    }
219
220    /// Returns true if the `Value` is an Array. Returns false otherwise.
221    pub fn is_array(&self) -> bool {
222        self.as_array().is_some()
223    }
224
225    /// If the `Value` is an Array, returns the associated vector.
226    /// Returns None otherwise.
227    pub fn as_array(&self) -> Option<&Vec<Value>> {
228        match *self {
229            Value::Array(ref array) => Some(array),
230            _ => None,
231        }
232    }
233
234    /// If the `Value` is an Array, returns the associated mutable vector.
235    /// Returns None otherwise.
236    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
237        match *self {
238            Value::Array(ref mut list) => Some(list),
239            _ => None,
240        }
241    }
242
243    /// Returns true if the `Value` is a String. Returns false otherwise.
244    pub fn is_string(&self) -> bool {
245        self.as_str().is_some()
246    }
247
248    /// If the `Value` is a String, returns the associated str.
249    /// Returns None otherwise.
250    pub fn as_str(&self) -> Option<&str> {
251        match *self {
252            Value::String(ref s) => Some(s),
253            _ => None,
254        }
255    }
256
257    /// Returns true if the `Value` is a Number. Returns false otherwise.
258    pub fn is_number(&self) -> bool {
259        match *self {
260            Value::I64(_) | Value::U64(_) | Value::F64(_) => true,
261            _ => false,
262        }
263    }
264
265    /// Returns true if the `Value` is a i64. Returns false otherwise.
266    pub fn is_i64(&self) -> bool {
267        match *self {
268            Value::I64(_) => true,
269            _ => false,
270        }
271    }
272
273    /// Returns true if the `Value` is a u64. Returns false otherwise.
274    pub fn is_u64(&self) -> bool {
275        match *self {
276            Value::U64(_) => true,
277            _ => false,
278        }
279    }
280
281    /// Returns true if the `Value` is a f64. Returns false otherwise.
282    pub fn is_f64(&self) -> bool {
283        match *self {
284            Value::F64(_) => true,
285            _ => false,
286        }
287    }
288
289    /// If the `Value` is a number, return or cast it to a i64.
290    /// Returns None otherwise.
291    pub fn as_i64(&self) -> Option<i64> {
292        match *self {
293            Value::I64(n) => Some(n),
294            Value::U64(n) => NumCast::from(n),
295            _ => None,
296        }
297    }
298
299    /// If the `Value` is a number, return or cast it to a u64.
300    /// Returns None otherwise.
301    pub fn as_u64(&self) -> Option<u64> {
302        match *self {
303            Value::I64(n) => NumCast::from(n),
304            Value::U64(n) => Some(n),
305            _ => None,
306        }
307    }
308
309    /// If the `Value` is a number, return or cast it to a f64.
310    /// Returns None otherwise.
311    pub fn as_f64(&self) -> Option<f64> {
312        match *self {
313            Value::I64(n) => NumCast::from(n),
314            Value::U64(n) => NumCast::from(n),
315            Value::F64(n) => Some(n),
316            _ => None,
317        }
318    }
319
320    /// Returns true if the `Value` is a Boolean. Returns false otherwise.
321    pub fn is_boolean(&self) -> bool {
322        self.as_bool().is_some()
323    }
324
325    /// If the `Value` is a Boolean, returns the associated bool.
326    /// Returns None otherwise.
327    pub fn as_bool(&self) -> Option<bool> {
328        match *self {
329            Value::Bool(b) => Some(b),
330            _ => None,
331        }
332    }
333
334    /// Returns true if the `Value` is a Null. Returns false otherwise.
335    pub fn is_null(&self) -> bool {
336        self.as_null().is_some()
337    }
338
339    /// If the `Value` is a Null, returns ().
340    /// Returns None otherwise.
341    pub fn as_null(&self) -> Option<()> {
342        match *self {
343            Value::Null => Some(()),
344            _ => None,
345        }
346    }
347
348    fn as_unexpected(&self) -> de::Unexpected<'_> {
349        match *self {
350            Value::Null => de::Unexpected::Unit,
351            Value::Bool(v) => de::Unexpected::Bool(v),
352            Value::I64(v) => de::Unexpected::Signed(v),
353            Value::U64(v) => de::Unexpected::Unsigned(v),
354            Value::F64(v) => de::Unexpected::Float(v),
355            Value::String(ref v) => de::Unexpected::Str(v),
356            Value::Array(_) => de::Unexpected::Seq,
357            Value::Object(_) => de::Unexpected::Map,
358        }
359    }
360}
361
362impl ser::Serialize for Value {
363    #[inline]
364    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
365    where
366        S: ser::Serializer,
367    {
368        match *self {
369            Value::Null => serializer.serialize_unit(),
370            Value::Bool(v) => serializer.serialize_bool(v),
371            Value::I64(v) => serializer.serialize_i64(v),
372            Value::U64(v) => serializer.serialize_u64(v),
373            Value::F64(v) => serializer.serialize_f64(v),
374            Value::String(ref v) => serializer.serialize_str(v),
375            Value::Array(ref v) => v.serialize(serializer),
376            Value::Object(ref v) => v.serialize(serializer),
377        }
378    }
379}
380
381impl<'de> de::Deserialize<'de> for Value {
382    #[inline]
383    fn deserialize<D>(deserializer: D) -> Result<Value, D::Error>
384    where
385        D: de::Deserializer<'de>,
386    {
387        struct ValueVisitor;
388
389        impl<'de> de::Visitor<'de> for ValueVisitor {
390            type Value = Value;
391
392            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
393                f.write_str("a json value")
394            }
395
396            #[inline]
397            fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
398                Ok(Value::Bool(value))
399            }
400
401            #[inline]
402            fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
403                if value < 0 {
404                    Ok(Value::I64(value))
405                } else {
406                    Ok(Value::U64(value as u64))
407                }
408            }
409
410            #[inline]
411            fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
412                Ok(Value::U64(value))
413            }
414
415            #[inline]
416            fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
417                Ok(Value::F64(value))
418            }
419
420            #[inline]
421            fn visit_str<E>(self, value: &str) -> Result<Value, E>
422            where
423                E: de::Error,
424            {
425                self.visit_string(String::from(value))
426            }
427
428            #[inline]
429            fn visit_string<E>(self, value: String) -> Result<Value, E> {
430                Ok(Value::String(value))
431            }
432
433            #[inline]
434            fn visit_none<E>(self) -> Result<Value, E> {
435                Ok(Value::Null)
436            }
437
438            #[inline]
439            fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error>
440            where
441                D: de::Deserializer<'de>,
442            {
443                de::Deserialize::deserialize(deserializer)
444            }
445
446            #[inline]
447            fn visit_unit<E>(self) -> Result<Value, E> {
448                Ok(Value::Null)
449            }
450
451            #[inline]
452            fn visit_seq<A>(self, mut seq: A) -> Result<Value, A::Error>
453            where
454                A: de::SeqAccess<'de>,
455            {
456                let mut v = match seq.size_hint() {
457                    Some(cap) => Vec::with_capacity(cap),
458                    None => Vec::new(),
459                };
460
461                while let Some(el) = seq.next_element()? {
462                    v.push(el);
463                }
464
465                Ok(Value::Array(v))
466            }
467
468            #[inline]
469            fn visit_map<A>(self, mut map: A) -> Result<Value, A::Error>
470            where
471                A: de::MapAccess<'de>,
472            {
473                let mut values = map_with_capacity(map.size_hint());
474                while let Some((k, v)) = map.next_entry()? {
475                    values.insert(k, v);
476                }
477                Ok(Value::Object(values))
478            }
479        }
480
481        deserializer.deserialize_any(ValueVisitor)
482    }
483}
484
485struct WriterFormatter<'a, 'b: 'a> {
486    inner: &'a mut fmt::Formatter<'b>,
487}
488
489impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
490    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
491        fn io_error<E>(_: E) -> io::Error {
492            // Value does not matter because fmt::Debug and fmt::Display impls
493            // below just map it to fmt::Error
494            io::Error::new(io::ErrorKind::Other, "fmt error")
495        }
496        let s = str::from_utf8(buf).map_err(io_error)?;
497        self.inner.write_str(s).map_err(io_error)?;
498        Ok(buf.len())
499    }
500
501    fn flush(&mut self) -> io::Result<()> {
502        Ok(())
503    }
504}
505
506impl fmt::Debug for Value {
507    /// Serializes a Hjson value into a string
508    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
509        let mut wr = WriterFormatter { inner: f };
510        super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
511    }
512}
513
514impl fmt::Display for Value {
515    /// Serializes a Hjson value into a string
516    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
517        let mut wr = WriterFormatter { inner: f };
518        super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
519    }
520}
521
522impl str::FromStr for Value {
523    type Err = Error;
524    fn from_str(s: &str) -> Result<Value> {
525        super::de::from_str(s)
526    }
527}
528
529/// Create a `serde::Serializer` that serializes a `Serialize`e into a `Value`.
530#[derive(Default)]
531pub struct Serializer;
532
533impl ser::Serializer for Serializer {
534    type Ok = Value;
535    type Error = Error;
536
537    type SerializeSeq = SerializeVec;
538    type SerializeTuple = SerializeVec;
539    type SerializeTupleStruct = SerializeVec;
540    type SerializeTupleVariant = SerializeTupleVariant;
541    type SerializeMap = SerializeMap;
542    type SerializeStruct = SerializeMap;
543    type SerializeStructVariant = SerializeStructVariant;
544
545    #[inline]
546    fn serialize_bool(self, value: bool) -> Result<Value> {
547        Ok(Value::Bool(value))
548    }
549
550    #[inline]
551    fn serialize_i8(self, value: i8) -> Result<Value> {
552        self.serialize_i64(value as i64)
553    }
554
555    #[inline]
556    fn serialize_i16(self, value: i16) -> Result<Value> {
557        self.serialize_i64(value as i64)
558    }
559
560    #[inline]
561    fn serialize_i32(self, value: i32) -> Result<Value> {
562        self.serialize_i64(value as i64)
563    }
564
565    fn serialize_i64(self, value: i64) -> Result<Value> {
566        let v = if value < 0 {
567            Value::I64(value)
568        } else {
569            Value::U64(value as u64)
570        };
571        Ok(v)
572    }
573
574    #[inline]
575    fn serialize_u8(self, value: u8) -> Result<Value> {
576        self.serialize_u64(value as u64)
577    }
578
579    #[inline]
580    fn serialize_u16(self, value: u16) -> Result<Value> {
581        self.serialize_u64(value as u64)
582    }
583
584    #[inline]
585    fn serialize_u32(self, value: u32) -> Result<Value> {
586        self.serialize_u64(value as u64)
587    }
588
589    #[inline]
590    fn serialize_u64(self, value: u64) -> Result<Value> {
591        Ok(Value::U64(value))
592    }
593
594    #[inline]
595    fn serialize_f32(self, value: f32) -> Result<Value> {
596        self.serialize_f64(value as f64)
597    }
598
599    #[inline]
600    fn serialize_f64(self, value: f64) -> Result<Value> {
601        Ok(Value::F64(value))
602    }
603
604    #[inline]
605    fn serialize_char(self, value: char) -> Result<Value> {
606        let mut s = String::new();
607        s.push(value);
608        self.serialize_str(&s)
609    }
610
611    #[inline]
612    fn serialize_str(self, value: &str) -> Result<Value> {
613        Ok(Value::String(String::from(value)))
614    }
615
616    fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
617        let mut state = self.serialize_seq(Some(value.len()))?;
618        for byte in value {
619            ser::SerializeSeq::serialize_element(&mut state, byte)?;
620        }
621        ser::SerializeSeq::end(state)
622    }
623
624    #[inline]
625    fn serialize_unit(self) -> Result<Value> {
626        Ok(Value::Null)
627    }
628
629    #[inline]
630    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
631        self.serialize_unit()
632    }
633
634    #[inline]
635    fn serialize_unit_variant(
636        self,
637        _name: &'static str,
638        _variant_index: u32,
639        variant: &'static str,
640    ) -> Result<Value> {
641        self.serialize_str(variant)
642    }
643
644    #[inline]
645    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
646    where
647        T: ?Sized + ser::Serialize,
648    {
649        value.serialize(self)
650    }
651
652    fn serialize_newtype_variant<T>(
653        self,
654        _name: &'static str,
655        _variant_index: u32,
656        variant: &'static str,
657        value: &T,
658    ) -> Result<Value>
659    where
660        T: ?Sized + ser::Serialize,
661    {
662        let mut values = Map::new();
663        values.insert(String::from(variant), to_value(&value)?);
664        Ok(Value::Object(values))
665    }
666
667    #[inline]
668    fn serialize_none(self) -> Result<Value> {
669        self.serialize_unit()
670    }
671
672    #[inline]
673    fn serialize_some<V>(self, value: &V) -> Result<Value>
674    where
675        V: ?Sized + ser::Serialize,
676    {
677        value.serialize(self)
678    }
679
680    #[inline]
681    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
682        Ok(SerializeVec {
683            vec: Vec::with_capacity(len.unwrap_or(0)),
684        })
685    }
686
687    #[inline]
688    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
689        self.serialize_seq(Some(len))
690    }
691
692    #[inline]
693    fn serialize_tuple_struct(
694        self,
695        _name: &'static str,
696        len: usize,
697    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
698        self.serialize_seq(Some(len))
699    }
700
701    #[inline]
702    fn serialize_tuple_variant(
703        self,
704        _name: &'static str,
705        _variant_index: u32,
706        variant: &'static str,
707        len: usize,
708    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
709        Ok(SerializeTupleVariant {
710            name: variant,
711            vec: Vec::with_capacity(len),
712        })
713    }
714
715    #[inline]
716    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
717        Ok(SerializeMap {
718            map: map_with_capacity(len),
719            next_key: None,
720        })
721    }
722
723    #[inline]
724    fn serialize_struct(
725        self,
726        _name: &'static str,
727        len: usize,
728    ) -> Result<Self::SerializeStruct, Self::Error> {
729        self.serialize_map(Some(len))
730    }
731
732    #[inline]
733    fn serialize_struct_variant(
734        self,
735        _name: &'static str,
736        _variant_index: u32,
737        variant: &'static str,
738        len: usize,
739    ) -> Result<Self::SerializeStructVariant, Self::Error> {
740        Ok(SerializeStructVariant {
741            name: variant,
742            map: map_with_capacity(Some(len)),
743        })
744    }
745}
746
747#[doc(hidden)]
748pub struct SerializeVec {
749    vec: Vec<Value>,
750}
751
752#[doc(hidden)]
753pub struct SerializeTupleVariant {
754    name: &'static str,
755    vec: Vec<Value>,
756}
757
758#[doc(hidden)]
759pub struct SerializeMap {
760    map: Map<String, Value>,
761    next_key: Option<String>,
762}
763
764#[doc(hidden)]
765pub struct SerializeStructVariant {
766    name: &'static str,
767    map: Map<String, Value>,
768}
769
770impl ser::SerializeSeq for SerializeVec {
771    type Ok = Value;
772    type Error = Error;
773
774    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
775    where
776        T: ?Sized + ser::Serialize,
777    {
778        self.vec.push(to_value(&value)?);
779        Ok(())
780    }
781
782    fn end(self) -> Result<Value> {
783        Ok(Value::Array(self.vec))
784    }
785}
786
787impl ser::SerializeTuple for SerializeVec {
788    type Ok = Value;
789    type Error = Error;
790
791    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
792    where
793        T: ?Sized + ser::Serialize,
794    {
795        ser::SerializeSeq::serialize_element(self, value)
796    }
797
798    fn end(self) -> Result<Value> {
799        ser::SerializeSeq::end(self)
800    }
801}
802
803impl ser::SerializeTupleStruct for SerializeVec {
804    type Ok = Value;
805    type Error = Error;
806
807    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
808    where
809        T: ?Sized + ser::Serialize,
810    {
811        ser::SerializeSeq::serialize_element(self, value)
812    }
813
814    fn end(self) -> Result<Value> {
815        ser::SerializeSeq::end(self)
816    }
817}
818
819impl ser::SerializeTupleVariant for SerializeTupleVariant {
820    type Ok = Value;
821    type Error = Error;
822
823    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
824    where
825        T: ?Sized + ser::Serialize,
826    {
827        self.vec.push(to_value(&value)?);
828        Ok(())
829    }
830
831    fn end(self) -> Result<Value> {
832        let mut object = Map::new();
833
834        object.insert(self.name.to_owned(), Value::Array(self.vec));
835
836        Ok(Value::Object(object))
837    }
838}
839
840impl ser::SerializeMap for SerializeMap {
841    type Ok = Value;
842    type Error = Error;
843
844    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
845    where
846        T: ?Sized + ser::Serialize,
847    {
848        match to_value(key)? {
849            Value::String(s) => self.next_key = Some(s),
850            _ => return Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)),
851        };
852        Ok(())
853    }
854
855    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
856    where
857        T: ?Sized + ser::Serialize,
858    {
859        let key = self.next_key.take();
860        // Panic because this indicates a bug in the program rather than an
861        // expected failure.
862        let key = key.expect("serialize_value called before serialize_key");
863        self.map.insert(key, to_value(value)?);
864        Ok(())
865    }
866
867    fn end(self) -> Result<Value> {
868        Ok(Value::Object(self.map))
869    }
870}
871
872impl ser::SerializeStruct for SerializeMap {
873    type Ok = Value;
874    type Error = Error;
875
876    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
877    where
878        T: ?Sized + ser::Serialize,
879    {
880        ser::SerializeMap::serialize_entry(self, key, value)
881    }
882
883    fn end(self) -> Result<Value> {
884        ser::SerializeMap::end(self)
885    }
886}
887
888impl ser::SerializeStructVariant for SerializeStructVariant {
889    type Ok = Value;
890    type Error = Error;
891
892    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
893    where
894        T: ?Sized + ser::Serialize,
895    {
896        self.map.insert(key.to_owned(), to_value(&value)?);
897        Ok(())
898    }
899
900    fn end(self) -> Result<Value> {
901        let mut object = map_with_capacity(Some(1));
902
903        object.insert(self.name.to_owned(), Value::Object(self.map));
904
905        Ok(Value::Object(object))
906    }
907}
908
909impl<'de> de::Deserializer<'de> for Value {
910    type Error = Error;
911
912    #[inline]
913    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
914    where
915        V: de::Visitor<'de>,
916    {
917        match self {
918            Value::Null => visitor.visit_unit(),
919            Value::Bool(v) => visitor.visit_bool(v),
920            Value::I64(v) => visitor.visit_i64(v),
921            Value::U64(v) => visitor.visit_u64(v),
922            Value::F64(v) => visitor.visit_f64(v),
923            Value::String(v) => visitor.visit_string(v),
924            Value::Array(v) => visitor.visit_seq(SeqDeserializer {
925                iter: v.into_iter(),
926            }),
927            Value::Object(v) => visitor.visit_map(MapDeserializer {
928                iter: v.into_iter(),
929                value: None,
930            }),
931        }
932    }
933
934    #[inline]
935    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
936    where
937        V: de::Visitor<'de>,
938    {
939        match self {
940            Value::Null => visitor.visit_none(),
941            _ => visitor.visit_some(self),
942        }
943    }
944
945    #[inline]
946    fn deserialize_enum<V>(
947        self,
948        _name: &str,
949        _variants: &'static [&'static str],
950        visitor: V,
951    ) -> Result<V::Value>
952    where
953        V: de::Visitor<'de>,
954    {
955        let (variant, value) = match self {
956            Value::Object(value) => {
957                let mut iter = value.into_iter();
958                let Some((variant, value)) = iter.next() else {
959                    return Err(de::Error::invalid_type(
960                        de::Unexpected::Map,
961                        &"map with a single key",
962                    ));
963                };
964                // enums are encoded in json as maps with a single key:value pair
965                if iter.next().is_some() {
966                    return Err(de::Error::invalid_type(
967                        de::Unexpected::Map,
968                        &"map with a single key",
969                    ));
970                }
971                (variant, Some(value))
972            }
973            Value::String(variant) => (variant, None),
974            val => {
975                return Err(de::Error::invalid_type(
976                    val.as_unexpected(),
977                    &"string or map",
978                ))
979            }
980        };
981
982        visitor.visit_enum(EnumDeserializer { value, variant })
983    }
984
985    #[inline]
986    fn deserialize_newtype_struct<V>(
987        self,
988        _name: &'static str,
989        visitor: V,
990    ) -> Result<V::Value, Self::Error>
991    where
992        V: de::Visitor<'de>,
993    {
994        visitor.visit_newtype_struct(self)
995    }
996
997    serde::forward_to_deserialize_any! {
998        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
999        bytes byte_buf unit unit_struct seq tuple
1000        tuple_struct map struct identifier ignored_any
1001    }
1002}
1003
1004struct EnumDeserializer {
1005    variant: String,
1006    value: Option<Value>,
1007}
1008
1009impl<'de> de::EnumAccess<'de> for EnumDeserializer {
1010    type Error = Error;
1011
1012    type Variant = VariantDeserializer;
1013
1014    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
1015    where
1016        V: de::DeserializeSeed<'de>,
1017    {
1018        let variant = de::IntoDeserializer::into_deserializer(self.variant);
1019        let visitor = VariantDeserializer { val: self.value };
1020        seed.deserialize(variant).map(|v| (v, visitor))
1021    }
1022}
1023
1024struct VariantDeserializer {
1025    val: Option<Value>,
1026}
1027
1028impl<'de> de::VariantAccess<'de> for VariantDeserializer {
1029    type Error = Error;
1030
1031    fn unit_variant(self) -> Result<()> {
1032        match self.val {
1033            Some(val) => de::Deserialize::deserialize(val),
1034            None => Ok(()),
1035        }
1036    }
1037
1038    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
1039    where
1040        T: de::DeserializeSeed<'de>,
1041    {
1042        match self.val {
1043            Some(value) => seed.deserialize(value),
1044            None => Err(serde::de::Error::invalid_type(
1045                de::Unexpected::UnitVariant,
1046                &"newtype variant",
1047            )),
1048        }
1049    }
1050
1051    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1052    where
1053        V: de::Visitor<'de>,
1054    {
1055        let val = self.val.expect("val is missing");
1056        if let Value::Array(fields) = val {
1057            visitor.visit_seq(SeqDeserializer {
1058                iter: fields.into_iter(),
1059            })
1060        } else {
1061            Err(de::Error::invalid_type(val.as_unexpected(), &visitor))
1062        }
1063    }
1064
1065    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
1066    where
1067        V: de::Visitor<'de>,
1068    {
1069        match self.val {
1070            Some(Value::Object(fields)) => visitor.visit_map(MapDeserializer {
1071                iter: fields.into_iter(),
1072                value: None,
1073            }),
1074            Some(other) => Err(de::Error::invalid_type(
1075                other.as_unexpected(),
1076                &"struct variant",
1077            )),
1078            None => Err(de::Error::invalid_type(
1079                de::Unexpected::UnitVariant,
1080                &"struct variant",
1081            )),
1082        }
1083    }
1084}
1085
1086struct SeqDeserializer {
1087    iter: vec::IntoIter<Value>,
1088}
1089
1090impl<'de> de::SeqAccess<'de> for SeqDeserializer {
1091    type Error = Error;
1092
1093    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1094    where
1095        T: de::DeserializeSeed<'de>,
1096    {
1097        match self.iter.next() {
1098            Some(value) => Ok(Some(seed.deserialize(value)?)),
1099            None => Ok(None),
1100        }
1101    }
1102
1103    fn size_hint(&self) -> Option<usize> {
1104        match self.iter.size_hint() {
1105            (lower, Some(upper)) if lower == upper => Some(upper),
1106            _ => None,
1107        }
1108    }
1109}
1110
1111struct MapDeserializer {
1112    iter: MapIntoIter<String, Value>,
1113    value: Option<Value>,
1114}
1115
1116impl<'de> de::MapAccess<'de> for MapDeserializer {
1117    type Error = Error;
1118
1119    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
1120    where
1121        K: de::DeserializeSeed<'de>,
1122    {
1123        match self.iter.next() {
1124            Some((key, value)) => {
1125                self.value = Some(value);
1126                Ok(Some(seed.deserialize(Value::String(key))?))
1127            }
1128            None => Ok(None),
1129        }
1130    }
1131
1132    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1133    where
1134        V: de::DeserializeSeed<'de>,
1135    {
1136        let value = self.value.take().expect("value is missing");
1137        seed.deserialize(value)
1138    }
1139
1140    fn size_hint(&self) -> Option<usize> {
1141        match self.iter.size_hint() {
1142            (lower, Some(upper)) if lower == upper => Some(upper),
1143            _ => None,
1144        }
1145    }
1146}
1147
1148/// Shortcut function to encode a `T` into a Hjson `Value`
1149///
1150/// ```rust
1151/// use serde_hjson::to_value;
1152/// let val = to_value("foo");
1153/// assert_eq!(val.unwrap().as_str(), Some("foo"))
1154/// ```
1155pub fn to_value<T>(value: &T) -> Result<Value>
1156where
1157    T: ser::Serialize + ?Sized,
1158{
1159    value.serialize(Serializer)
1160}
1161
1162/// Shortcut function to decode a Hjson `Value` into a `T`
1163pub fn from_value<T>(value: Value) -> Result<T>
1164where
1165    T: de::DeserializeOwned,
1166{
1167    de::Deserialize::deserialize(value)
1168}
1169
1170/// A trait for converting values to Hjson
1171pub trait ToJson {
1172    /// Converts the value of `self` to an instance of Hjson
1173    fn to_json(&self) -> Value;
1174}
1175
1176impl<T: ?Sized> ToJson for T
1177where
1178    T: ser::Serialize,
1179{
1180    fn to_json(&self) -> Value {
1181        to_value(&self).expect("failed to serialize")
1182    }
1183}
1184
1185#[cfg(test)]
1186mod test {
1187    use super::super::de::from_str;
1188    use super::Value;
1189
1190    #[test]
1191    fn number_deserialize() {
1192        let v: Value = from_str("{\"a\":1}").unwrap();
1193        let vo = v.as_object().unwrap();
1194        assert_eq!(vo["a"].as_u64().unwrap(), 1);
1195
1196        let v: Value = from_str("{\"a\":-1}").unwrap();
1197        let vo = v.as_object().unwrap();
1198        assert_eq!(vo["a"].as_i64().unwrap(), -1);
1199
1200        let v: Value = from_str("{\"a\":1.1}").unwrap();
1201        let vo = v.as_object().unwrap();
1202        assert_eq!(vo["a"].as_f64().unwrap(), 1.1);
1203
1204        let v: Value = from_str("{\"a\":-1.1}").unwrap();
1205        let vo = v.as_object().unwrap();
1206        assert_eq!(vo["a"].as_f64().unwrap(), -1.1);
1207
1208        let v: Value = from_str("{\"a\":1e6}").unwrap();
1209        let vo = v.as_object().unwrap();
1210        assert_eq!(vo["a"].as_f64().unwrap(), 1e6);
1211
1212        let v: Value = from_str("{\"a\":-1e6}").unwrap();
1213        let vo = v.as_object().unwrap();
1214        assert_eq!(vo["a"].as_f64().unwrap(), -1e6);
1215    }
1216}