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
// License: see LICENSE file at root directory of `master` branch

//! # Value

use {
    alloc::{
        collections::BTreeMap,
        string::{String, ToString},
        vec::Vec,
    },
    core::{
        convert::TryFrom,
        fmt::{self, Display, Formatter, Write as _},
        iter::FromIterator,
    },
    crate::{
        Error, Number,
        bytes,
    },
};

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

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

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

const DEFAULT_TAB_WIDTH: usize = 4;

/// # A value
///
/// ## Usage
///
/// ### Formatting as JSON string
///
/// - To format as compacted JSON string, you can use `to_string()` or implementation of `From<Value> for Vec<u8>`.
///
/// - To format with default tab width (`4`), you can use `#` (via [`Formatter`][core::fmt/Formatter]):
///
///     ```
///     # #[cfg(feature="std")]
///     format!(
///         "{:#}",
///         sj::parse(&mut &br#"["test"]"#[..]).unwrap(),
///     );
///     ```
///
/// - You can set tab width (required) and tab level (optional):
///
///     ```
///     # #[cfg(feature="std")]
///     format!(
///         "{:width$.level$}",
///         sj::parse(&mut &br#"["test"]"#[..]).unwrap(),
///         width=4, level=0,
///     );
///     ```
///
/// ### 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.
///
/// ```
/// let mut object = sj::object();
/// object.insert("first", true)?;
/// object.insert("second", Some(9))?;
/// object.insert(String::from("third"), "...")?;
/// assert!(object.as_mut_object()?.remove("second").is_some());
/// assert_eq!(object.to_string(), r#"{"first":true,"third":"..."}"#);
///
/// let mut array = sj::array();
/// array.push(false)?;
/// array.push("a string")?;
/// array.push(Some(sj::object()))?;
/// 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
///
/// [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),

}

impl Value {

    /// # 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(array.push(value.into())),
            _ => Err(Error::from(__!("Value is not an Array"))),
        }
    }

    /// # 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(object.insert(key.into(), value.into())),
            _ => Err(Error::from(__!("Value is not an Object"))),
        }
    }

    /// # 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"))),
        }
    }

    /// # 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(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::from(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 Display for Value {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        // Notes:
        //
        // - Do NOT use Formatter::width()! Instead, use make_width_from_formatter()

        match self {
            Value::String(s) => format_string(s, f),
            Value::Number(n) => f.write_str(&n.to_string()),
            Value::Boolean(b) => f.write_str(&b.to_string()),
            Value::Null => f.write_str("null"),
            Value::Object(object) => {
                f.write_char('{')?;
                format_object_content(object, f)?;

                if object.is_empty() == false {
                    if let Some(pad) = make_pad_from_formatter(f) {
                        f.write_str(&pad)?;
                    }
                }
                f.write_char('}')
            },
            Value::Array(array) => {
                f.write_char('[')?;
                format_array_content(array, f)?;

                if array.is_empty() == false {
                    if let Some(pad) = make_pad_from_formatter(f) {
                        f.write_str(&pad)?;
                    }
                }
                f.write_char(']')
            },
        }
    }

}

impl From<Value> for Vec<u8> {

    fn from(value: Value) -> Self {
        value.to_string().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))
}

const LINE_BREAK: char = '\n';
const QUOTATION_MARK: char = '"';

/// # Formats string
fn format_string(s: &str, f: &mut Formatter) -> Result<(), fmt::Error> {
    f.write_char(QUOTATION_MARK)?;

    for c in s.chars() {
        match c {
            '"' | '\\' => {
                f.write_char('\\')?;
                f.write_char(c)?;
            },
            bytes::BACKSPACE_CHAR => f.write_str(concat!('\\', 'b'))?,
            bytes::FORM_FEED_CHAR => f.write_str(concat!('\\', 'f'))?,
            '\n' => f.write_str(concat!('\\', 'n'))?,
            '\r' => f.write_str(concat!('\\', 'r'))?,
            '\t' => f.write_str(concat!('\\', 't'))?,
            _ => f.write_char(c)?,
        };
    }

    f.write_char(QUOTATION_MARK)
}

/// # Makes pad from width and level
fn make_pad(width: Option<usize>, level: Option<usize>) -> Option<String> {
    match (width, level) {
        (Some(width), Some(level)) if width > 0 && level > 0 => Some(concat!(' ').repeat(width.saturating_mul(level))),
        _ => None,
    }
}

/// # Makes width from a formatter
fn make_width_from_formatter(f: &Formatter) -> Option<usize> {
    let result = f.width();
    match result.is_none() && f.alternate() {
        true => Some(DEFAULT_TAB_WIDTH),
        false => result,
    }
}

/// # Makes pad from a formatter
fn make_pad_from_formatter(f: &Formatter) -> Option<String> {
    make_pad(make_width_from_formatter(f), f.precision())
}

/// # Makes sub pad from a formatter
fn make_sub_pad_from_formatter(f: &Formatter) -> Option<String> {
    let width = make_width_from_formatter(f);
    let has_width = width.is_some();
    make_pad(width, match has_width {
        true => Some(f.precision().unwrap_or(0).saturating_add(1)),
        false => None,
    })
}

/// # Formats array content
fn format_array_content(array: &Array, f: &mut Formatter) -> Result<(), fmt::Error> {
    let pad = make_sub_pad_from_formatter(f);

    for (i, v) in array.iter().enumerate() {
        match i {
            0 => if pad.is_some() {
                f.write_char(LINE_BREAK)?;
            },
            _ => {
                f.write_char(',')?;
                if pad.is_some() {
                    f.write_char(LINE_BREAK)?;
                }
            },
        };

        if let Some(pad) = pad.as_ref() {
            f.write_str(pad)?;
        }

        format_sub_value(v, f)?;
    }

    match pad.is_some() && array.is_empty() == false {
        true => f.write_char(LINE_BREAK),
        false => Ok(()),
    }
}

/// # Formats object content
fn format_object_content(object: &Object, f: &mut Formatter) -> Result<(), fmt::Error> {
    let pad = make_sub_pad_from_formatter(f);

    for (i, (k, v)) in object.iter().enumerate() {
        match i {
            0 => if pad.is_some() {
                f.write_char(LINE_BREAK)?;
            },
            _ => {
                f.write_char(',')?;
                if pad.is_some() {
                    f.write_char(LINE_BREAK)?;
                }
            },
        };

        if let Some(pad) = pad.as_ref() {
            f.write_str(pad)?;
        }

        f.write_char(QUOTATION_MARK)?;
        f.write_str(k)?;
        f.write_str(concat!('"', ':'))?;
        if pad.is_some() {
            f.write_char(' ')?;
        }

        format_sub_value(v, f)?;
    }

    match pad.is_some() && object.is_empty() == false {
        true => f.write_char(LINE_BREAK),
        false => Ok(()),
    }
}

/// # Formats a sub value
fn format_sub_value(value: &Value, f: &mut Formatter) -> Result<(), fmt::Error> {
    match make_width_from_formatter(f) {
        Some(width) => {
            let precision = f.precision().unwrap_or(0).saturating_add(1);
            write!(f, "{:width$.precision$}", value, width=width, precision=precision)
        },
        None => value.fmt(f),
    }
}