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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

SJ

Copyright (C) 2019-2024  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2019-2024".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # Json

mod array_indexes;
mod formatter;
mod impls;
mod object_indexes;

use {
    alloc::{
        string::String,
        vec::Vec,
    },
    crate::Number,
};

#[cfg(feature="std")]
use {
    core::str::FromStr,
    std::io::Write,
    crate::{Error, IoResult},
    self::formatter::*,
};

pub use self::{
    array_indexes::*,
    object_indexes::*,
};

/// # Array
///
/// ## Shortcuts
///
/// <small>[`array()`], [`array_with_capacity()`], [`push()`]</small>
///
/// [`array()`]: fn.array.html
/// [`array_with_capacity()`]: fn.array_with_capacity.html
/// [`push()`]: fn.push.html
pub type Array = Vec<Json>;

/// # Object
///
/// This uses [`BTreeMap`][struct:alloc/collections/BTreeMap].
///
/// ## Shortcuts
///
/// <small>[`object()`], [`insert()`]</small>
///
/// [`object()`]: fn.object.html
/// [`insert()`]: fn.insert.html
/// [struct:alloc/collections/BTreeMap]: https://doc.rust-lang.org/alloc/collections/btree_map/struct.BTreeMap.html
pub type Object = alloc::collections::BTreeMap<ObjectKey, Json>;

/// # Object key
pub type ObjectKey = String;

/// # Json
///
/// ## Formatting
///
/// ### Formatting as JSON string
///
/// - To format as compacted JSON string, you can use [`format()`][fn:Json#format] or [`format_as_bytes()`][fn:Json#format_as_bytes].
/// - To format as a nice JSON string, you can use [`format_nicely()`][fn:Json#format_nicely].
/// - Currently the order of keys in input objects will not be preserved. See [`Object`][type:Object] for more details.
///
/// ### Writing as JSON string to [`Write`][trait:std/io/Write]
///
/// Can be done via [`write()`][fn:Json#write] or [`write_nicely()`][fn:Json#write_nicely].
///
/// ## Converting Rust types to `Json` and vice versa
///
/// There are some implementations:
///
/// ```ignore
/// impl From<...> for Json;
/// impl TryFrom<&Json> for ...;
/// impl TryFrom<Json> for ...;
/// ```
///
/// About [`TryFrom`][trait: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`][enum-variant:Json#String], [`Object`][enum-variant:Json#Object],
///   [`Array`][enum-variant:Json#Array]..., 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:
///
///     ```
///     # #[cfg(feature="std")]
///     # fn test() -> sj::IoResult<()> {
///
///     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")?)?);
///     assert!(object.take_by("second")?.map_or(true)?);
///     assert!(
///         [r#"{"first":true,"third":"..."}"#, r#"{"third":"...","first":true}"#]
///             .contains(&object.format()?.as_str())
///     );
///     # Ok(()) }
///     # #[cfg(feature="std")]
///     # test().unwrap();
///     # Ok::<_, sj::Error>(())
///     ```
///
/// - Array:
///
///     ```
///     # #[cfg(feature="std")]
///     # fn test() -> sj::IoResult<()> {
///
///     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.format()?, r#"[false,"a string",{}]"#);
///     # Ok(()) }
///     # #[cfg(feature="std")]
///     # test().unwrap();
///     # Ok::<_, sj::Error>(())
///     ```
///
/// [trait:core/convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html
/// [trait:std/io/Write]: https://doc.rust-lang.org/std/io/trait.Write.html
///
/// [enum-variant:Json#Array]: #variant.Array
/// [enum-variant:Json#Object]: #variant.Object
/// [enum-variant:Json#String]: #variant.String
/// [fn:Json#format]: #method.format
/// [fn:Json#format_nicely]: #method.format_nicely
/// [fn:Json#format_as_bytes]: #method.format_as_bytes
/// [fn:Json#write]: #method.write
/// [fn:Json#write_nicely]: #method.write_nicely
/// [type:Object]: type.Object.html
#[derive(Debug, Clone)]
pub enum Json {

    /// [_Shortcuts_](#shortcuts-for-string)
    String(String),

    /// ### Shortcuts
    ///
    /// <small>[`TryFrom`][trait:core/convert/TryFrom]</small>
    ///
    /// [trait:core/convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html
    Number(Number),

    /// ### Shortcuts
    ///
    /// <small>[`TryFrom`][trait:core/convert/TryFrom]</small>
    ///
    /// [trait:core/convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html
    Boolean(bool),

    /// [_Shortcuts_](#shortcuts-for-null)
    Null,

    /// [_Shortcuts_](#shortcuts-for-object)
    Object(Object),

    /// [_Shortcuts_](#shortcuts-for-array)
    Array(Array),

}

impl Json {

    /// # Formats this value as a compacted JSON string
    #[cfg(feature="std")]
    #[doc(cfg(feature="std"))]
    pub fn format_as_bytes(&self) -> IoResult<Vec<u8>> {
        let mut buf = Vec::with_capacity(formatter::estimate_format_size(self, None, None));
        self.write(&mut buf)?;
        buf.flush().map(|()| buf)
    }

    /// # Nicely formats this value as JSON string
    ///
    /// If you don't provide tab size, default (`4`) will be used.
    #[cfg(feature="std")]
    #[doc(cfg(feature="std"))]
    pub fn format_nicely_as_bytes(&self, tab: Option<u8>) -> IoResult<Vec<u8>> {
        let mut buf = Vec::with_capacity(formatter::estimate_format_size(self, Some(tab.unwrap_or(formatter::DEFAULT_TAB_WIDTH)), None));
        self.write_nicely(tab, &mut buf)?;
        buf.flush().map(|()| buf)
    }

    /// # Formats this value as a compacted JSON string
    #[cfg(feature="std")]
    #[doc(cfg(feature="std"))]
    pub fn format(&self) -> IoResult<String> {
        #[allow(unsafe_code)]
        Ok(unsafe {
            String::from_utf8_unchecked(self.format_as_bytes()?)
        })
    }

    /// # Nicely formats this value as JSON string
    ///
    /// If you don't provide tab size, default (`4`) will be used.
    #[cfg(feature="std")]
    #[doc(cfg(feature="std"))]
    pub fn format_nicely(&self, tab: Option<u8>) -> IoResult<String> {
        #[allow(unsafe_code)]
        Ok(unsafe {
            String::from_utf8_unchecked(self.format_nicely_as_bytes(tab)?)
        })
    }

    /// # Writes this value as compacted JSON string to a stream
    ///
    /// ## Notes
    ///
    /// - The stream is used as-is. You might want to consider using [`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")]
    #[doc(cfg(feature="std"))]
    pub fn write<W>(&self, stream: &mut W) -> IoResult<()> where W: Write {
        Formatter::new(None).format(self, stream)
    }

    /// # 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. You might want to consider using [`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")]
    #[doc(cfg(feature="std"))]
    pub fn write_nicely<W>(&self, tab: Option<u8>, stream: &mut W) -> IoResult<()> where W: Write {
        let tab = match tab {
            Some(_) => tab,
            None => Some(formatter::DEFAULT_TAB_WIDTH),
        };
        Formatter::new(tab).format(self, stream)
    }

}

impl Default for Json {

    fn default() -> Self {
        Self::Null
    }

}

#[cfg(feature="std")]
#[doc(cfg(feature="std"))]
impl FromStr for Json {

    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        crate::parse_bytes(s)
    }

}

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

    type Error = Error;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        crate::parse_bytes(bytes)
    }

}

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

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

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

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

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