1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// License: see LICENSE file at root directory of `master` branch

//! # Value

mod impls;

use {
    alloc::{
        collections::BTreeMap,
        string::{String, ToString},
        vec::Vec,
    },
    core::{
        convert::TryFrom,
        iter::FromIterator,
    },
    crate::{Error, Number},
};

#[cfg(feature="std")]
use {
    std::io::Write,
    crate::IoResult,
};

/// # Array
pub type Array = Vec<Value>;

/// # Object
pub type Object = BTreeMap<String, Value>;

/// # A value
///
/// ## Formatting
///
/// ### Formatting as JSON string
///
/// - To format as compacted JSON string, you can use `to_string()` or implementation of `From<Value> for Vec<u8>`, or
///   [`into_bytes()`][into_bytes()].
///
/// - To format with default tab width (`4`), you can use `#` (via [`Formatter`][core::fmt/Formatter]):
///
///     ```
///     # #[cfg(feature="std")]
///     format!("{:#}", sj::parse_bytes("[0]")?);
///     # Ok::<_, sj::Error>(())
///     ```
///
/// - You can set tab width (required) and tab level (optional):
///
///     ```
///     # #[cfg(feature="std")]
///     format!("{:width$.level$}", sj::parse_bytes("[null]")?, width=4, level=0);
///     # Ok::<_, sj::Error>(())
///     ```
///
/// ### Writing as JSON string to [`Write`][std::io/Write]
///
/// Can be done via [`write()`][write()] or [`write_nicely()`][write_nicely()].
///
/// ## Converting Rust types to `Value` and vice versa
///
/// There are some implementations:
///
/// ```ignore
/// impl From<...> for Value;
/// impl TryFrom<&Value> for ...;
/// impl TryFrom<Value> for ...;
/// ```
///
/// About [`TryFrom`][core::convert/TryFrom] implementations:
///
/// - For primitives, since they're cheap, they have implementations on either a borrowed or an owned value.
/// - For collections such as [`String`][alloc::string/String], [`Vec`][alloc::vec/Vec]..., they only have implementations on an owned value. So
///   data is moved, not copied.
///
/// ## Shortcuts
///
/// A root JSON value can be either an object or an array. For your convenience, there are some shortcuts, like below examples.
///
/// - Object:
///
///     ```
///     use core::convert::TryFrom;
///
///     let mut object = sj::object();
///     object.insert("first", true)?;
///     object.insert("second", <Option<u8>>::None)?;
///     object.insert(String::from("third"), "...")?;
///
///     assert!(bool::try_from(object.by(&["first"])?.unwrap())?);
///     assert!(object.take_by(&["second"])?.unwrap().try_into_or(true)?);
///     assert_eq!(object.to_string(), r#"{"first":true,"third":"..."}"#);
///
///     # Ok::<_, sj::Error>(())
///     ```
///
/// - Array:
///
///     ```
///     use core::convert::TryFrom;
///
///     let mut array = sj::array();
///     array.push(false)?;
///     array.push("a string")?;
///     array.push(Some(sj::object()))?;
///
///     assert!(bool::try_from(array.at(&[0])?)? == false);
///     assert_eq!(array.to_string(), r#"[false,"a string",{}]"#);
///
///     # Ok::<_, sj::Error>(())
///     ```
///
/// [alloc::string/String]: https://doc.rust-lang.org/alloc/string/struct.String.html
/// [alloc::vec/Vec]: https://doc.rust-lang.org/alloc/vec/struct.Vec.html
/// [core::convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html
/// [core::fmt/Formatter]: https://doc.rust-lang.org/core/fmt/struct.Formatter.html
/// [std::bool]: https://doc.rust-lang.org/std/primitive.bool.html
/// [std::io/Write]: https://doc.rust-lang.org/std/io/trait.Write.html
///
/// [into_bytes()]: #method.into_bytes
/// [write()]: #method.write
/// [write_nicely()]: #method.write_nicely
#[derive(Debug)]
pub enum Value {

    /// # String
    String(String),

    /// # Number
    Number(Number),

    /// # Boolean
    Boolean(bool),

    /// # Null
    Null,

    /// # Object
    Object(Object),

    /// # Array
    Array(Array),

}

/// # Helper macro for Value::at()/mut_at()
macro_rules! at_or_mut_at { ($self: ident, $indexes: ident, $code: tt) => {{
    let mut value = Some($self);
    for (nth, idx) in $indexes.iter().enumerate() {
        match value {
            Some(Value::Array(array)) => {
                value = array.$code(*idx);
                if nth + 1 == $indexes.len() {
                    return value.ok_or_else(|| Error::from(__!("Indexes are invalid: {:?}", $indexes)));
                }
            },
            Some(_) => return Err(Error::from(match nth {
                0 => __!("Value is not an Array"),
                _ => __!("Value at {:?} is not an Array", &$indexes[..nth]),
            })),
            None => return Err(Error::from(__!("There is no value at {:?}", &$indexes[..nth]))),
        };
    }

    Err(Error::from(__!("Indexes must not be empty")))
}}}

/// # Helper macro for Value::by()/mut_by()
macro_rules! by_or_mut_by { ($self: ident, $keys: ident, $code: tt) => {{
    if $keys.is_empty() {
        return Err(Error::from(__!("Keys must not be empty")));
    }

    let mut value = Some($self);
    for (nth, key) in $keys.iter().enumerate() {
        match value {
            Some(Value::Object(object)) => value = object.$code(*key),
            Some(_) => return Err(Error::from(match nth {
                0 => __!("Value is not an Object"),
                _ => __!("Value at {:?} is not an Object", &$keys[..nth]),
            })),
            None => return Err(Error::from(__!("There is no value at {:?}", &$keys[..nth]))),
        };
    }

    Ok(value)
}}}

impl Value {

    /// # Formats this value as a compacted JSON string
    pub fn into_bytes(self) -> Vec<u8> {
        self.to_string().into_bytes()
    }

    /// # Tries to convert this value into something
    ///
    /// If this is [`Null`][Null], returns `default`.
    ///
    /// If your default value would be a result of a function call, you should use [`try_into_or_else()`][try_into_or_else()].
    ///
    /// ## Examples
    ///
    /// ```
    /// # #[cfg(feature="std")] {
    /// let mut value = sj::parse_bytes("[null]")?;
    /// assert!(value.take_at(&[0])?.try_into_or(true)?);
    /// # }
    /// # Ok::<_, sj::Error>(())
    /// ```
    ///
    /// [Null]: #variant.Null
    /// [try_into_or_else()]: #method.try_into_or_else
    pub fn try_into_or<T>(self, default: T) -> crate::Result<T> where T: TryFrom<Self, Error=Error> {
        match self {
            Value::Null => Ok(default),
            _ => T::try_from(self),
        }
    }

    /// # Tries to convert this value into something
    ///
    /// If this is [`Null`][Null], calls `default()` and returns its result.
    ///
    /// ## See also
    ///
    /// [`try_into_or()`][try_into_or()]
    ///
    /// [Null]: #variant.Null
    /// [try_into_or()]: #method.try_into_or
    pub fn try_into_or_else<T, F>(self, default: F) -> crate::Result<T> where T: TryFrom<Self, Error=Error>, F: FnOnce() -> T {
        match self {
            Value::Null => Ok(default()),
            _ => T::try_from(self),
        }
    }

    /// # Tries to convert a reference of this value into something
    ///
    /// If this is [`Null`][Null], returns `default`.
    ///
    /// If your default value would be a result of a function call, you should use [`try_ref_into_or_else()`][try_ref_into_or_else()].
    ///
    /// ## Examples
    ///
    /// ```
    /// # #[cfg(feature="std")] {
    /// let value = sj::parse_bytes("[null]")?;
    /// assert_eq!(value.at(&[0])?.try_ref_into_or(0)?, 0);
    /// # }
    /// # Ok::<_, sj::Error>(())
    /// ```
    ///
    /// [Null]: #variant.Null
    /// [try_ref_into_or_else()]: #method.try_ref_into_or_else
    pub fn try_ref_into_or<'a, T>(&'a self, default: T) -> crate::Result<T> where T: TryFrom<&'a Self, Error=Error> {
        match self {
            Value::Null => Ok(default),
            _ => T::try_from(self),
        }
    }

    /// # Tries to convert a reference of this value into something
    ///
    /// If this is [`Null`][Null], calls `default()` and returns its result.
    ///
    /// ## See also
    ///
    /// [`try_ref_into_or()`][try_ref_into_or()]
    ///
    /// [Null]: #variant.Null
    /// [try_ref_into_or()]: #method.try_ref_into_or
    pub fn try_ref_into_or_else<'a, T, F>(&'a self, default: F) -> crate::Result<T> where T: TryFrom<&'a Self, Error=Error>, F: FnOnce() -> T {
        match self {
            Value::Null => Ok(default()),
            _ => T::try_from(self),
        }
    }

    /// # If the value is a string, returns an immutable reference of it
    ///
    /// Returns an error if the value is not a string.
    pub fn as_str(&self) -> crate::Result<&str> {
        match self {
            Value::String(s) => Ok(s),
            _ => Err(Error::from(__!("Value is not a String"))),
        }
    }

    /// # If the value is an array, pushes new item into it
    ///
    /// Returns an error if the value is not an array.
    pub fn push<T>(&mut self, value: T) -> crate::Result<()> where T: Into<Self> {
        match self {
            Value::Array(array) => Ok(push(array, value)),
            _ => Err(Error::from(__!("Value is not an Array"))),
        }
    }

    /// # Gets an immutable item from this array and its sub arrays
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Indexes are empty or invalid.
    /// - The value or any of its sub items is not an array.
    ///
    /// ## Examples
    ///
    /// ```
    /// let mut array = sj::array();
    /// array.push("first")?;
    /// array.push(vec![false.into(), "second".into()])?;
    ///
    /// assert_eq!(array.at(&[0])?.as_str()?, "first");
    /// assert_eq!(array.at(&[1, 1])?.as_str()?, "second");
    ///
    /// assert!(array.at(&[]).is_err());
    /// assert!(array.at(&[0, 1]).is_err());
    /// assert!(array.at(&[1, 2]).is_err());
    /// assert!(array.at(&[1, 0, 0]).is_err());
    /// assert!(array.at(&[1, 1, 2]).is_err());
    ///
    /// # Ok::<_, sj::Error>(())
    /// ```
    pub fn at(&self, indexes: &[usize]) -> crate::Result<&Self> {
        at_or_mut_at!(self, indexes, get)
    }

    /// # Gets a mutable item from this array and its sub arrays
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Indexes are empty or invalid.
    /// - The value or any of its sub items is not an array.
    ///
    /// ## See also
    ///
    /// [`at()`][at()]
    ///
    /// [at()]: #method.at
    pub fn mut_at(&mut self, indexes: &[usize]) -> crate::Result<&mut Self> {
        at_or_mut_at!(self, indexes, get_mut)
    }

    /// # Takes an item from this array and its sub arrays
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Indexes are empty or invalid.
    /// - The value or any of its sub items is not an array.
    ///
    /// ## Examples
    ///
    /// ```
    /// let mut array = sj::array();
    /// array.push("earth")?;
    /// array.push(vec![false.into(), "moon".into()])?;
    ///
    /// assert_eq!(array.take_at(&[0])?.as_str()?, "earth");
    /// assert_eq!(array.take_at(&[0, 1])?.as_str()?, "moon");
    ///
    /// assert!(array.take_at(&[]).is_err());
    /// assert!(array.take_at(&[0, 1]).is_err());
    ///
    /// # Ok::<_, sj::Error>(())
    /// ```
    pub fn take_at(&mut self, indexes: &[usize]) -> crate::Result<Self> {
        let mut value = Some(self);
        for (nth, idx) in indexes.iter().enumerate() {
            match value {
                Some(Value::Array(array)) => match nth + 1 == indexes.len() {
                    true => return match idx >= &0 && idx < &array.len() {
                        true => Ok(array.remove(*idx)),
                        false => Err(Error::from(__!("Invalid indexes: {:?}", indexes))),
                    },
                    false => value = array.get_mut(*idx),
                },
                Some(_) => return Err(Error::from(match nth {
                    0 => __!("Value is not an Array"),
                    _ => __!("Value at {:?} is not an Array", &indexes[..nth]),
                })),
                None => return Err(Error::from(__!("There is no value at {:?}", &indexes[..nth]))),
            };
        }

        Err(Error::from(__!("Indexes must not be empty")))
    }

    /// # If the value is an array, returns an immutable reference of it
    ///
    /// Returns an error if the value is not an array.
    pub fn as_array(&self) -> crate::Result<&Array> {
        match self {
            Value::Array(array) => Ok(array),
            _ => Err(Error::from(__!("Value is not an Array"))),
        }
    }

    /// # If the value is an array, returns a mutable reference of it
    ///
    /// Returns an error if the value is not an array.
    pub fn as_mut_array(&mut self) -> crate::Result<&mut Array> {
        match self {
            Value::Array(array) => Ok(array),
            _ => Err(Error::from(__!("Value is not an Array"))),
        }
    }

    /// # If the value is an object, inserts new item into it
    ///
    /// On success, returns previous value (if it existed).
    ///
    /// Returns an error if the value is not an object.
    pub fn insert<S, T>(&mut self, key: S, value: T) -> crate::Result<Option<Self>> where S: Into<String>, T: Into<Self> {
        match self {
            Value::Object(object) => Ok(insert(object, key, value)),
            _ => Err(Error::from(__!("Value is not an Object"))),
        }
    }

    /// # Gets an immutable item from this object and its sub objects
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not an object.
    ///
    /// ## Examples
    ///
    /// ```
    /// use core::convert::TryFrom;
    ///
    /// let mut object = sj::object();
    /// object.insert("first", true)?;
    /// object.insert("second", {
    ///     let mut map = sj::Object::new();
    ///     sj::insert(&mut map, "zero", 0);
    ///     map
    /// })?;
    ///
    /// assert_eq!(bool::try_from(object.by(&["first"])?.unwrap())?, true);
    /// assert_eq!(u8::try_from(object.by(&["second", "zero"])?.unwrap())?, 0);
    ///
    /// assert!(object.by(&["something"])?.is_none());
    ///
    /// assert!(object.by(&[]).is_err());
    /// assert!(object.by(&["first", "last"]).is_err());
    /// assert!(object.by(&["second", "third", "fourth"]).is_err());
    ///
    /// # Ok::<_, sj::Error>(())
    /// ```
    pub fn by(&self, keys: &[&str]) -> crate::Result<Option<&Self>> {
        by_or_mut_by!(self, keys, get)
    }

    /// # Gets a mutable item from this object and its sub objects
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not an object.
    ///
    /// ## See also
    ///
    /// [`by()`][by()]
    ///
    /// [by()]: #method.by
    pub fn mut_by(&mut self, keys: &[&str]) -> crate::Result<Option<&mut Self>> {
        by_or_mut_by!(self, keys, get_mut)
    }

    /// # Takes an item from this object and its sub objects
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not an object.
    ///
    /// ## Examples
    ///
    /// ```
    /// let mut object = sj::object();
    /// object.insert("earth", "moon")?;
    /// object.insert("solar-system", {
    ///     let mut map = sj::Object::new();
    ///     sj::insert(&mut map, "sun", "earth");
    ///     map
    /// })?;
    ///
    /// assert_eq!(object.take_by(&["earth"])?.unwrap().as_str()?, "moon");
    /// assert_eq!(object.take_by(&["solar-system", "sun"])?.unwrap().as_str()?, "earth");
    ///
    /// assert!(object.take_by(&["milky-way"])?.is_none());
    /// assert!(object.take_by(&["solar-system", "mars"])?.is_none());
    ///
    /// assert!(object.take_by(&[]).is_err());
    /// assert!(object.take_by(&["jupiter", "venus"]).is_err());
    ///
    /// # Ok::<_, sj::Error>(())
    /// ```
    pub fn take_by(&mut self, keys: &[&str]) -> crate::Result<Option<Self>> {
        let mut value = Some(self);
        for (nth, key) in keys.iter().enumerate() {
            match value {
                Some(Value::Object(object)) => match nth + 1 == keys.len() {
                    true => return Ok(object.remove(*key)),
                    false => value = object.get_mut(*key),
                },
                Some(_) => return Err(Error::from(match nth {
                    0 => __!("Value is not an Object"),
                    _ => __!("Value at {:?} is not an Object", &keys[..nth]),
                })),
                None => return Err(Error::from(__!("There is no value at {:?}", &keys[..nth]))),
            };
        }

        Err(Error::from(__!("Keys must not be empty")))
    }

    /// # If the value is an object, returns an immutable reference of it
    ///
    /// Returns an error if the value is not an object.
    pub fn as_object(&self) -> crate::Result<&Object> {
        match self {
            Value::Object(object) => Ok(object),
            _ => Err(Error::from(__!("Value is not an Object"))),
        }
    }

    /// # If the value is an object, returns a mutable reference of it
    ///
    /// Returns an error if the value is not an object.
    pub fn as_mut_object(&mut self) -> crate::Result<&mut Object> {
        match self {
            Value::Object(object) => Ok(object),
            _ => Err(Error::from(__!("Value is not an Object"))),
        }
    }

    /// # Checks to see if this value is [`Null`][Null]
    ///
    /// [Null]: #variant.Null
    pub fn is_null(&self) -> bool {
        match self {
            Value::Null => true,
            _ => false,
        }
    }

    /// # Writes this value as compacted JSON string to a stream
    ///
    /// ## Notes
    ///
    /// - The stream is used as-is. For better performance, you _should_ wrap your stream inside a [`BufWriter`][std::io/BufWriter].
    /// - This function does **not** flush the stream when done.
    ///
    /// [std::io/BufWriter]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
    #[cfg(feature="std")]
    pub fn write<W>(&self, stream: &mut W) -> IoResult<()> where W: Write {
        write!(stream, concat!('{', '}'), self)
    }

    /// # Writes this value as nicely formatted JSON string to a stream
    ///
    /// ## Notes
    ///
    /// - If you don't provide tab size, default (`4`) will be used.
    /// - The stream is used as-is. For better performance, you _should_ wrap your stream inside a [`BufWriter`][std::io/BufWriter].
    /// - This function does **not** flush the stream when done.
    ///
    /// [std::io/BufWriter]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
    #[cfg(feature="std")]
    pub fn write_nicely<W>(&self, tab: Option<usize>, stream: &mut W) -> IoResult<()> where W: Write {
        write!(stream, concat!('{', ":tab$", '}'), self, tab=tab.unwrap_or(impls::display::DEFAULT_TAB_WIDTH))
    }

}

impl From<String> for Value {

    fn from(s: String) -> Self {
        Value::String(s)
    }

}

impl From<&str> for Value {

    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }

}

impl TryFrom<Value> for String {

    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::String(s) => Ok(s),
            _ => Err(Error::from(__!("Value is not a String"))),
        }
    }

}

impl From<Number> for Value {

    fn from(n: Number) -> Self {
        Value::Number(n)
    }

}

impl From<bool> for Value {

    fn from(b: bool) -> Self {
        Value::Boolean(b)
    }

}

impl TryFrom<&Value> for bool {

    type Error = Error;

    fn try_from(value: &Value) -> Result<Self, Self::Error> {
        match value {
            Value::Boolean(b) => Ok(*b),
            _ => Err(Error::from(__!("Value is not a Boolean"))),
        }
    }

}

impl TryFrom<Value> for bool {

    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }

}

impl From<Object> for Value {

    fn from(map: Object) -> Self {
        Value::Object(map)
    }

}

impl FromIterator<(String, Value)> for Value {

    fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=(String, Value)> {
        Value::Object(iter.into_iter().collect())
    }

}

impl TryFrom<Value> for Object {

    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Object(object) => Ok(object),
            _ => Err(Error::from(__!("Value is not an Object"))),
        }
    }

}

impl From<Array> for Value {

    fn from(values: Array) -> Self {
        Value::Array(values)
    }

}

impl FromIterator<Value> for Value {

    fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=Value> {
        Value::Array(iter.into_iter().collect())
    }

}

impl TryFrom<Value> for Array {

    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Array(array) => Ok(array),
            _ => Err(Error::from(__!("Value is not an Array"))),
        }
    }

}

impl<T> From<Option<T>> for Value where T: Into<Value> {

    fn from(t: Option<T>) -> Self {
        match t {
            Some(t) => t.into(),
            None => Value::Null,
        }
    }

}

macro_rules! impl_from_primitives_for_value { ($($ty: ty, $code: tt,)+) => {
    $(
        impl From<$ty> for Value {

            fn from(n: $ty) -> Self {
                Value::Number(Number::$code(n))
            }

        }
    )+
}}

impl_from_primitives_for_value! {
    i8, I8, i16, I16, i32, I32, i64, I64, i128, I128, isize, ISize,
    u8, U8, u16, U16, u32, U32, u64, U64, u128, U128, usize, USize,
    f32, F32, f64, F64,
}

macro_rules! impl_try_from_value_for_primitives { ($($ty: ty,)+) => {
    $(
        impl TryFrom<&Value> for $ty {

            type Error = Error;

            fn try_from(value: &Value) -> Result<Self, Self::Error> {
                match value {
                    Value::Number(n) => Self::try_from(n),
                    _ => Err(Error::from(__!("Value is not a Number"))),
                }
            }

        }

        impl TryFrom<Value> for $ty {

            type Error = Error;

            fn try_from(value: Value) -> Result<Self, Self::Error> {
                Self::try_from(&value)
            }

        }
    )+
}}

impl_try_from_value_for_primitives! {
    i8, i16, i32, i64, i128, isize,
    u8, u16, u32, u64, u128, usize,
    f32, f64,
}

impl From<Value> for Vec<u8> {

    fn from(value: Value) -> Self {
        value.into_bytes()
    }

}

#[cfg(feature="std")]
impl TryFrom<Vec<u8>> for Value {

    type Error = Error;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        crate::parse(&mut bytes.as_slice())
    }

}

/// # Makes new object
pub fn object() -> Value {
    Value::Object(Object::new())
}

/// # Makes new array
pub fn array() -> Value {
    Value::Array(Vec::new())
}

/// # Makes new array with capacity
pub fn array_with_capacity(capacity: usize) -> Value {
    Value::Array(Vec::with_capacity(capacity))
}

/// # Pushes new item into an array
pub fn push<T>(array: &mut Array, value: T) where T: Into<Value> {
    array.push(value.into());
}

/// # Inserts new item into an object
///
/// Returns previous value (if it existed).
pub fn insert<S, T>(object: &mut Object, key: S, value: T) -> Option<Value> where S: Into<String>, T: Into<Value> {
    object.insert(key.into(), value.into())
}