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
use std::ops::{Index, IndexMut, Deref};
use std::convert::TryInto;
use std::{fmt, mem, usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32};
use std::io::{self, Write};

use crate::{Result, Error};
use crate::short::Short;
use crate::number::Number;
use crate::object::Object;
use crate::iterators::{ Members, MembersMut, Entries, EntriesMut };
use crate::codegen::{ Generator, PrettyGenerator, DumpGenerator, WriterGenerator, PrettyWriterGenerator };

mod implements;

// These are convenience macros for converting `f64` to the `$unsigned` type.
// The macros check that the numbers are representable the target type.
macro_rules! number_to_unsigned {
    ($unsigned:ident, $value:expr, $high:ty) => {
        if $value > $unsigned::MAX as $high {
            None
        } else {
            Some($value as $unsigned)
        }
    }
}

macro_rules! number_to_signed {
    ($signed:ident, $value:expr, $high:ty) => {
        if $value < $signed::MIN as $high || $value > $signed::MAX as $high {
            None
        } else {
            Some($value as $signed)
        }
    }
}

#[derive(Debug, Clone)]
pub enum JsonValue {
    Null,
    Short(Short),
    String(String),
    Number(Number),
    Boolean(bool),
    Object(Object),
    Array(Vec<JsonValue>),
}

impl PartialEq for JsonValue {
    fn eq(&self, other: &Self) -> bool {
        use self::JsonValue::*;
        match (self, other) {
            (&Null, &Null) => true,
            (&Short(ref a), &Short(ref b)) => a == b,
            (&String(ref a), &String(ref b)) => a == b,
            (&Short(ref a), &String(ref b))
            | (&String(ref b), &Short(ref a)) => a.as_str() == b.as_str(),
            (&Number(ref a), &Number(ref b)) => a == b,
            (&Boolean(ref a), &Boolean(ref b)) => a == b,
            (&Object(ref a), &Object(ref b)) => a == b,
            (&Array(ref a), &Array(ref b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for JsonValue {}

/// Implements formatting
///
/// ```
/// # use json;
/// let data = json::parse(r#"{"url":"https://github.com/"}"#).unwrap();
/// println!("{}", data);
/// println!("{:#}", data);
/// ```
impl fmt::Display for JsonValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if f.alternate() {
            f.write_str(&self.pretty(4))
        } else {
            match *self {
                JsonValue::Short(ref value)   => value.fmt(f),
                JsonValue::String(ref value)  => value.fmt(f),
                JsonValue::Number(ref value)  => value.fmt(f),
                JsonValue::Boolean(ref value) => value.fmt(f),
                JsonValue::Null               => f.write_str("null"),
                _                             => f.write_str(&self.dump())
            }
        }
    }
}


static NULL: JsonValue = JsonValue::Null;

impl JsonValue {
    /// Create an empty `JsonValue::Object` instance.
    /// When creating an object with data, consider using the `object!` macro.
    pub fn new_object() -> JsonValue {
        JsonValue::Object(Object::new())
    }

    /// Create an empty `JsonValue::Array` instance.
    /// When creating array with data, consider using the `array!` macro.
    pub fn new_array() -> JsonValue {
        JsonValue::Array(Vec::new())
    }

    /// Prints out the value as JSON string.
    pub fn dump(&self) -> String {
        let mut gen = DumpGenerator::new();
        gen.write_json(self).expect("Can't fail");
        gen.consume()
    }

    /// Pretty prints out the value as JSON string. Takes an argument that's
    /// number of spaces to indent new blocks with.
    pub fn pretty(&self, spaces: u16) -> String {
        let mut gen = PrettyGenerator::new(spaces);
        gen.write_json(self).expect("Can't fail");
        gen.consume()
    }

    /// Writes the JSON as byte stream into an implementor of `std::io::Write`.
    ///
    /// This method is deprecated as it will panic on io errors, use `write` instead.
    #[deprecated(since="0.10.2", note="use `JsonValue::write` instead")]
    pub fn to_writer<W: Write>(&self, writer: &mut W) {
        let mut gen = WriterGenerator::new(writer);
        gen.write_json(self).expect("Deprecated");
    }

    /// Writes the JSON as byte stream into an implementor of `std::io::Write`.
    pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        let mut gen = WriterGenerator::new(writer);
        gen.write_json(self)
    }

    /// Writes the JSON as byte stream into an implementor of `std::io::Write`.
    pub fn write_pretty<W: Write>(&self, writer: &mut W, spaces: u16) -> io::Result<()> {
        let mut gen = PrettyWriterGenerator::new(writer, spaces);
        gen.write_json(self)
    }

    pub fn is_string(&self) -> bool {
        match *self {
            JsonValue::Short(_)  => true,
            JsonValue::String(_) => true,
            _                    => false,
        }
    }

    pub fn is_number(&self) -> bool {
        match *self {
            JsonValue::Number(_) => true,
            _                    => false,
        }
    }

    pub fn is_boolean(&self) -> bool {
        match *self {
            JsonValue::Boolean(_) => true,
            _                     => false
        }
    }

    pub fn is_null(&self) -> bool {
        match *self {
            JsonValue::Null => true,
            _               => false,
        }
    }

    pub fn is_object(&self) -> bool {
        match *self {
            JsonValue::Object(_) => true,
            _                    => false,
        }
    }

    pub fn is_array(&self) -> bool {
        match *self {
            JsonValue::Array(_) => true,
            _                   => false,
        }
    }

    /// Checks whether the value is empty. Returns true for:
    ///
    /// - empty string (`""`)
    /// - number `0`
    /// - boolean `false`
    /// - null
    /// - empty array (`array![]`)
    /// - empty object (`object!{}`)
    pub fn is_empty(&self) -> bool {
        match *self {
            JsonValue::Null               => true,
            JsonValue::Short(ref value)   => value.is_empty(),
            JsonValue::String(ref value)  => value.is_empty(),
            JsonValue::Number(ref value)  => value.is_empty(),
            JsonValue::Boolean(ref value) => !value,
            JsonValue::Array(ref value)   => value.is_empty(),
            JsonValue::Object(ref value)  => value.is_empty(),
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match *self {
            JsonValue::Short(ref value)  => Some(value),
            JsonValue::String(ref value) => Some(value),
            _                            => None
        }
    }

    pub fn as_number(&self) -> Option<Number> {
        match *self {
            JsonValue::Number(value) => Some(value),
            _                        => None
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        self.as_number().map(|value| value.into())
    }

    pub fn as_f32(&self) -> Option<f32> {
        self.as_number().map(|value| value.into())
    }

    pub fn as_u64(&self) -> Option<u64> {
        self.as_number().and_then(|value| {
            value.try_into().ok()
        })
    }

    pub fn as_u32(&self) -> Option<u32> {
        self.as_u64().and_then(|value| number_to_unsigned!(u32, value, u64))
    }

    pub fn as_u16(&self) -> Option<u16> {
        self.as_u64().and_then(|value| number_to_unsigned!(u16, value, u64))
    }

    pub fn as_u8(&self) -> Option<u8> {
        self.as_u64().and_then(|value| number_to_unsigned!(u8, value, u64))
    }

    pub fn as_usize(&self) -> Option<usize> {
        self.as_u64().and_then(|value| number_to_unsigned!(usize, value, u64))
    }

    pub fn as_i64(&self) -> Option<i64> {
        self.as_number().and_then(|value| value.try_into().ok())
    }

    pub fn as_i32(&self) -> Option<i32> {
        self.as_i64().and_then(|value| number_to_signed!(i32, value, i64))
    }

    pub fn as_i16(&self) -> Option<i16> {
        self.as_i64().and_then(|value| number_to_signed!(i16, value, i64))
    }

    pub fn as_i8(&self) -> Option<i8> {
        self.as_i64().and_then(|value| number_to_signed!(i8, value, i64))
    }

    pub fn as_isize(&self) -> Option<isize> {
        self.as_i64().and_then(|value| number_to_signed!(isize, value, i64))
    }

    pub fn as_bool(&self) -> Option<bool> {
        match *self {
            JsonValue::Boolean(ref value) => Some(*value),
            _                             => None
        }
    }

    /// Obtain an integer at a fixed decimal point. This is useful for
    /// converting monetary values and doing arithmetic on them without
    /// rounding errors introduced by floating point operations.
    ///
    /// Will return `None` if `Number` called on a value that's not a number,
    /// or if the number is negative or a NaN.
    ///
    /// ```
    /// # use json::JsonValue;
    /// let price_a = JsonValue::from(5.99);
    /// let price_b = JsonValue::from(7);
    /// let price_c = JsonValue::from(10.2);
    ///
    /// assert_eq!(price_a.as_fixed_point_u64(2), Some(599));
    /// assert_eq!(price_b.as_fixed_point_u64(2), Some(700));
    /// assert_eq!(price_c.as_fixed_point_u64(2), Some(1020));
    /// ```
    pub fn as_fixed_point_u64(&self, point: u16) -> Option<u64> {
        match *self {
            JsonValue::Number(ref value) => value.as_fixed_point_u64(point),
            _                            => None
        }
    }

    /// Analog to `as_fixed_point_u64`, except returning a signed
    /// `i64`, properly handling negative numbers.
    ///
    /// ```
    /// # use json::JsonValue;
    /// let balance_a = JsonValue::from(-1.49);
    /// let balance_b = JsonValue::from(42);
    ///
    /// assert_eq!(balance_a.as_fixed_point_i64(2), Some(-149));
    /// assert_eq!(balance_b.as_fixed_point_i64(2), Some(4200));
    /// ```
    pub fn as_fixed_point_i64(&self, point: u16) -> Option<i64> {
        match *self {
            JsonValue::Number(ref value) => value.as_fixed_point_i64(point),
            _                            => None
        }
    }

    /// Take over the ownership of the value, leaving `Null` in it's place.
    ///
    /// ## Example
    ///
    /// ```
    /// # #[macro_use] extern crate json;
    /// # fn main() {
    /// let mut data = array!["Foo", 42];
    ///
    /// let first = data[0].take();
    /// let second = data[1].take();
    ///
    /// assert!(first == "Foo");
    /// assert!(second == 42);
    ///
    /// assert!(data[0].is_null());
    /// assert!(data[1].is_null());
    /// # }
    /// ```
    pub fn take(&mut self) -> JsonValue {
        mem::replace(self, JsonValue::Null)
    }

    /// Checks that self is a string, returns an owned Rust `String`, leaving
    /// `Null` in it's place.
    ///
    /// - If the contained string is already a heap allocated `String`, then
    /// the ownership is moved without any heap allocation.
    ///
    /// - If the contained string is a `Short`, this will perform a heap
    /// allocation to convert the types for you.
    ///
    /// ## Example
    ///
    /// ```
    /// # #[macro_use] extern crate json;
    /// # fn main() {
    /// let mut data = array!["Hello", "World"];
    ///
    /// let owned = data[0].take_string().expect("Should be a string");
    ///
    /// assert_eq!(owned, "Hello");
    /// assert!(data[0].is_null());
    /// # }
    /// ```
    pub fn take_string(&mut self) -> Option<String> {
        let mut placeholder = JsonValue::Null;

        mem::swap(self, &mut placeholder);

        match placeholder {
            JsonValue::Short(short)   => return Some(short.into()),
            JsonValue::String(string) => return Some(string),

            // Not a string? Swap the original value back in place!
            _ => mem::swap(self, &mut placeholder)
        }

        None
    }

    /// Works on `JsonValue::Array` - pushes a new value to the array.
    pub fn push<T>(&mut self, value: T) -> Result<()>
    where T: Into<JsonValue> {
        match *self {
            JsonValue::Array(ref mut vec) => {
                vec.push(value.into());
                Ok(())
            },
            _ => Err(Error::wrong_type("Array"))
        }
    }

    /// Works on `JsonValue::Array` - remove and return last element from
    /// an array. On failure returns a null.
    pub fn pop(&mut self) -> JsonValue {
        match *self {
            JsonValue::Array(ref mut vec) => {
                vec.pop().unwrap_or(JsonValue::Null)
            },
            _ => JsonValue::Null
        }
    }

    /// Works on `JsonValue::Array` - checks if the array contains a value
    pub fn contains<T>(&self, item: T) -> bool where T: PartialEq<JsonValue> {
        match *self {
            JsonValue::Array(ref vec) => vec.iter().any(|member| item == *member),
            _                         => false
        }
    }

    /// Works on `JsonValue::Object` - checks if the object has a key
    pub fn has_key(&self, key: &str) -> bool {
        match *self {
            JsonValue::Object(ref object) => object.get(key).is_some(),
            _                             => false
        }
    }

    /// Returns length of array or object (number of keys), defaults to `0` for
    /// other types.
    pub fn len(&self) -> usize {
        match *self {
            JsonValue::Array(ref vec) => {
                vec.len()
            },
            JsonValue::Object(ref object) => {
                object.len()
            },
            _ => 0
        }
    }

    /// Works on `JsonValue::Array` - returns an iterator over members.
    /// Will return an empty iterator if called on non-array types.
    pub fn members(&self) -> Members {
        match *self {
            JsonValue::Array(ref vec) => {
                vec.iter()
            },
            _ => [].iter()
        }
    }

    /// Works on `JsonValue::Array` - returns a mutable iterator over members.
    /// Will return an empty iterator if called on non-array types.
    pub fn members_mut(&mut self) -> MembersMut {
        match *self {
            JsonValue::Array(ref mut vec) => {
                vec.iter_mut()
            },
            _ => [].iter_mut()
        }
    }

    /// Works on `JsonValue::Object` - returns an iterator over key value pairs.
    /// Will return an empty iterator if called on non-object types.
    pub fn entries(&self) -> Entries {
        match *self {
            JsonValue::Object(ref object) => {
                object.iter()
            },
            _ => Entries::empty()
        }
    }

    /// Works on `JsonValue::Object` - returns a mutable iterator over
    /// key value pairs.
    /// Will return an empty iterator if called on non-object types.
    pub fn entries_mut(&mut self) -> EntriesMut {
        match *self {
            JsonValue::Object(ref mut object) => {
                object.iter_mut()
            },
            _ => EntriesMut::empty()
        }
    }

    /// Works on `JsonValue::Object` - inserts a new entry, or override an existing
    /// one into the object. Note that `key` has to be a `&str` slice and not an owned
    /// `String`. The internals of `Object` will handle the heap allocation of the key
    /// if needed for better performance.
    pub fn insert<T>(&mut self, key: &str, value: T) -> Result<()>
    where T: Into<JsonValue> {
        match *self {
            JsonValue::Object(ref mut object) => {
                object.insert(key, value.into());
                Ok(())
            },
            _ => Err(Error::wrong_type("Object"))
        }
    }

    /// Works on `JsonValue::Object` - remove a key and return the value it held.
    /// If the key was not present, the method is called on anything but an
    /// object, it will return a null.
    pub fn remove(&mut self, key: &str) -> JsonValue {
        match *self {
            JsonValue::Object(ref mut object) => {
                object.remove(key).unwrap_or(JsonValue::Null)
            },
            _ => JsonValue::Null
        }
    }

    /// Works on `JsonValue::Array` - remove an entry and return the value it held.
    /// If the method is called on anything but an object or if the index is out of bounds, it
    /// will return `JsonValue::Null`.
    pub fn array_remove(&mut self, index: usize) -> JsonValue {
        match *self {
            JsonValue::Array(ref mut vec) => {
                if index < vec.len() {
                    vec.remove(index)
                } else {
                    JsonValue::Null
                }
            },
            _ => JsonValue::Null
        }
    }

    /// When called on an array or an object, will wipe them clean. When called
    /// on a string will clear the string. Numbers and booleans become null.
    pub fn clear(&mut self) {
        match *self {
            JsonValue::String(ref mut string) => string.clear(),
            JsonValue::Object(ref mut object) => object.clear(),
            JsonValue::Array(ref mut vec)     => vec.clear(),
            _                                 => *self = JsonValue::Null,
        }
    }
}

/// Implements indexing by `usize` to easily access array members:
///
/// ## Example
///
/// ```
/// # use json::JsonValue;
/// let mut array = JsonValue::new_array();
///
/// array.push("foo");
///
/// assert!(array[0] == "foo");
/// ```
impl Index<usize> for JsonValue {
    type Output = JsonValue;

    fn index(&self, index: usize) -> &JsonValue {
        match *self {
            JsonValue::Array(ref vec) => vec.get(index).unwrap_or(&NULL),
            _ => &NULL
        }
    }
}

/// Implements mutable indexing by `usize` to easily modify array members:
///
/// ## Example
///
/// ```
/// # #[macro_use]
/// # extern crate json;
/// #
/// # fn main() {
/// let mut array = array!["foo", 3.14];
///
/// array[1] = "bar".into();
///
/// assert!(array[1] == "bar");
/// # }
/// ```
impl IndexMut<usize> for JsonValue {
    fn index_mut(&mut self, index: usize) -> &mut JsonValue {
        match *self {
            JsonValue::Array(ref mut vec) => {
                let in_bounds = index < vec.len();

                if in_bounds {
                    &mut vec[index]
                } else {
                    vec.push(JsonValue::Null);
                    vec.last_mut().unwrap()
                }
            }
            _ => {
                *self = JsonValue::new_array();
                self.push(JsonValue::Null).unwrap();
                self.index_mut(index)
            }
        }
    }
}

/// Implements indexing by `&str` to easily access object members:
///
/// ## Example
///
/// ```
/// # #[macro_use]
/// # extern crate json;
/// #
/// # fn main() {
/// let object = object!{
///     "foo" => "bar"
/// };
///
/// assert!(object["foo"] == "bar");
/// # }
/// ```
impl<'a> Index<&'a str> for JsonValue {
    type Output = JsonValue;

    fn index(&self, index: &str) -> &JsonValue {
        match *self {
            JsonValue::Object(ref object) => &object[index],
            _ => &NULL
        }
    }
}

impl Index<String> for JsonValue {
    type Output = JsonValue;

    fn index(&self, index: String) -> &JsonValue {
        self.index(index.deref())
    }
}

impl<'a> Index<&'a String> for JsonValue {
    type Output = JsonValue;

    fn index(&self, index: &String) -> &JsonValue {
        self.index(index.deref())
    }
}

/// Implements mutable indexing by `&str` to easily modify object members:
///
/// ## Example
///
/// ```
/// # #[macro_use]
/// # extern crate json;
/// #
/// # fn main() {
/// let mut object = object!{};
///
/// object["foo"] = 42.into();
///
/// assert!(object["foo"] == 42);
/// # }
/// ```
impl<'a> IndexMut<&'a str> for JsonValue {
    fn index_mut(&mut self, index: &str) -> &mut JsonValue {
        match *self {
            JsonValue::Object(ref mut object) => {
                &mut object[index]
            },
            _ => {
                *self = JsonValue::new_object();
                self.index_mut(index)
            }
        }
    }
}

impl IndexMut<String> for JsonValue {
    fn index_mut(&mut self, index: String) -> &mut JsonValue {
        self.index_mut(index.deref())
    }
}

impl<'a> IndexMut<&'a String> for JsonValue {
    fn index_mut(&mut self, index: &String) -> &mut JsonValue {
        self.index_mut(index.deref())
    }
}