reqrio_json/
lib.rs

1use serde_json;
2use std::fmt::{Debug, Display, Formatter};
3use std::io;
4use std::num::{ParseFloatError, ParseIntError};
5use std::pin::Pin;
6use std::slice::{Iter, IterMut};
7use std::string::FromUtf8Error;
8use std::task::{Context, Poll};
9use std::vec::IntoIter;
10use serde::{Deserialize, Serialize};
11use serde_json::Error;
12use object::Object;
13use crate::number::Number;
14use crate::object::{ObjectIntoIter, ObjectIter, ObjectIterMut};
15use crate::parser::JsonParser;
16
17mod object;
18// mod fmt;
19mod parser;
20mod json_impl;
21pub mod number;
22pub mod ext;
23
24pub struct JsonError {
25    msg: String,
26}
27
28impl Debug for JsonError {
29    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
30        f.write_str(&self.msg)
31    }
32}
33
34impl Display for JsonError {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        f.write_str(&self.msg)
37    }
38}
39
40unsafe impl Send for JsonError {}
41
42impl Future for JsonError {
43    type Output = String;
44
45    fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
46        let poll = Poll::from(self.msg.clone());
47        poll
48    }
49}
50
51impl From<&str> for JsonError {
52    fn from(msg: &str) -> Self {
53        JsonError { msg: msg.to_string() }
54    }
55}
56
57impl From<ParseFloatError> for JsonError {
58    fn from(err: ParseFloatError) -> Self {
59        JsonError { msg: err.to_string() }
60    }
61}
62
63impl From<mh_json::Error> for JsonError {
64    fn from(err: mh_json::Error) -> Self {
65        JsonError { msg: err.to_string() }
66    }
67}
68
69impl From<io::Error> for JsonError {
70    fn from(value: io::Error) -> Self {
71        JsonError { msg: value.to_string() }
72    }
73}
74
75impl From<FromUtf8Error> for JsonError {
76    fn from(value: FromUtf8Error) -> Self {
77        JsonError { msg: value.to_string() }
78    }
79}
80
81impl From<ParseIntError> for JsonError {
82    fn from(value: ParseIntError) -> Self {
83        JsonError { msg: value.to_string() }
84    }
85}
86
87impl From<Error> for JsonError {
88    fn from(value: Error) -> Self {
89        JsonError { msg: value.to_string() }
90    }
91}
92
93impl std::error::Error for JsonError {}
94
95
96type JsonResult<T> = Result<T, JsonError>;
97
98static NULL: JsonValue = JsonValue::Null;
99
100pub fn parse(source: impl AsRef<str>) -> JsonResult<JsonValue> {
101    let parser = JsonParser::new();
102    let json_source = mh_json::parse(source.as_ref())?;
103    parser.parse_json(json_source)
104}
105
106pub fn from_file(fp: impl AsRef<str>) -> JsonResult<JsonValue> {
107    let b = std::fs::read(fp.as_ref())?;
108    let s = String::from_utf8(b)?;
109    parse(s.as_str())
110}
111
112pub fn from_bytes(context: &[u8]) -> JsonResult<JsonValue> {
113    let s = String::from_utf8(context.to_vec())?;
114    parse(s.as_str())
115}
116
117pub fn to_string<T: Serialize>(t: &T) -> JsonResult<String> {
118    Ok(serde_json::to_string(t)?)
119}
120
121pub fn from_struct<T: Serialize>(t: &T) -> JsonResult<JsonValue> {
122    let s = to_string(t)?;
123    parse(s.as_str())
124}
125
126
127#[derive(Clone)]
128pub enum JsonValue {
129    Null,
130    String(String),
131    Number(Number),
132    Boolean(bool),
133    Object(Object),
134    Array(Vec<JsonValue>),
135}
136
137impl Display for JsonValue {
138    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
139        if f.alternate() {
140            f.write_str(&self.pretty(4))
141        } else {
142            f.write_str(self.dump().as_str())
143        }
144    }
145}
146
147impl JsonValue {
148    pub fn new_object() -> JsonValue {
149        JsonValue::Object(Object::new())
150    }
151
152    pub fn new_array() -> JsonValue {
153        JsonValue::Array(vec![])
154    }
155
156    pub fn push<T>(&mut self, value: T)
157    where
158        T: Into<JsonValue>,
159    {
160        match self {
161            JsonValue::Array(vec) => vec.push(value.into()),
162            _ => {}
163        }
164    }
165
166    pub fn len(&self) -> usize {
167        match *self {
168            JsonValue::Array(ref vec) => vec.len(),
169            JsonValue::Object(ref object) => object.len(),
170            _ => 0
171        }
172    }
173
174    pub fn insert<T>(&mut self, key: &str, value: T) -> JsonResult<()>
175    where
176        T: Into<JsonValue>,
177    {
178        match self {
179            JsonValue::Object(o) => { Ok(o.insert(key, value.into())) }
180            _ => Err("Wrong Type Object!".into())
181        }
182    }
183
184    pub fn pretty(&self, spaces: u16) -> String {
185        let res = <JsonValue as Into<mh_json::JsonValue>>::into(self.clone());
186        res.pretty(spaces)
187    }
188
189    pub fn dump(&self) -> String {
190        let res = <JsonValue as Into<mh_json::JsonValue>>::into(self.clone());
191        match res {
192            mh_json::JsonValue::String(s) => s,
193            _ => res.dump()
194        }
195    }
196
197    pub fn has_key(&self, key: &str) -> bool {
198        match *self {
199            JsonValue::Object(ref object) => !object.get(key).is_null(),
200            _ => false
201        }
202    }
203
204    pub fn members(&self) -> Iter<'_, JsonValue> {
205        match self {
206            JsonValue::Array(vec) => vec.iter(),
207            _ => [].iter()
208        }
209    }
210
211    pub fn members_mut(&mut self) -> IterMut<'_, JsonValue> {
212        match self {
213            JsonValue::Array(vec) => vec.iter_mut(),
214            _ => [].iter_mut()
215        }
216    }
217
218    pub fn into_members(self) -> IntoIter<JsonValue> {
219        match self {
220            JsonValue::Array(vec) => vec.into_iter(),
221            _ => vec![].into_iter()
222        }
223    }
224
225    pub fn entries(&self) -> ObjectIter<'_> {
226        match self {
227            JsonValue::Object(object) => object.iter(),
228            _ => ObjectIter::empty()
229        }
230    }
231
232    pub fn entries_mut(&mut self) -> ObjectIterMut<'_> {
233        match self {
234            JsonValue::Object(object) => object.iter_mut(),
235            _ => ObjectIterMut::empty()
236        }
237    }
238
239    pub fn into_entries(self) -> ObjectIntoIter {
240        match self {
241            JsonValue::Object(object) => object.into_iter(),
242            _ => ObjectIntoIter::empty()
243        }
244    }
245
246    pub fn clear(&mut self) {
247        match self {
248            JsonValue::String(string) => string.clear(),
249            JsonValue::Object(object) => object.clear(),
250            JsonValue::Array(vec) => vec.clear(),
251            _ => *self = JsonValue::Null,
252        }
253    }
254
255    pub fn remove(&mut self, key: &str) -> JsonValue {
256        match self {
257            JsonValue::Object(object) => object.remove(key),
258            _ => JsonValue::Null,
259        }
260    }
261
262    pub fn array_remove(&mut self, index: usize) -> JsonValue {
263        match self {
264            JsonValue::Array(array) => { array.remove(index) }
265            _ => JsonValue::Null
266        }
267    }
268
269    /// must update_first
270    pub fn as_struct<T: for<'a> Deserialize<'a>>(&self) -> JsonResult<T> {
271        let s = self.dump();
272        Ok(serde_json::from_str(s.as_str())?)
273    }
274
275    pub fn write_file(&self, fp: impl AsRef<str>) -> JsonResult<()> {
276        std::fs::write(fp.as_ref(), self.pretty(2))?;
277        Ok(())
278    }
279
280    fn update(json1: &mut JsonValue, json2: JsonValue) -> JsonResult<()> {
281        for (k, v) in json2.entries() {
282            if v.is_object() && json1.has_key(k) {
283                if json1[k].is_null() {
284                    json1[k] = JsonValue::new_object();
285                }
286                if !json1[k].is_object() {
287                    json1[k] = JsonValue::new_object();
288                }
289                Self::update(&mut json1[k], json2[k].clone())?;
290                continue;
291            } else if v.is_object() && !json1.has_key(k) {
292                if json1[k].is_null() {
293                    json1[k] = JsonValue::new_array()
294                }
295                if !json1[k].is_array() {
296                    json1[k] = JsonValue::new_array();
297                }
298                json1.insert(k, json2[k].clone())?;
299                continue;
300            }
301            json1.insert(k, json2[k].clone())?;
302        }
303        Ok(())
304    }
305
306    pub fn update_by(&mut self, other: JsonValue) -> JsonResult<()> {
307        Self::update(self, other)
308    }
309
310    fn set_by_xpath(&mut self, xp: &[String], value: JsonValue) -> JsonResult<()> {
311        if xp.len() != 0 {
312            if xp[0].starts_with("[") && xp[0].ends_with("]") {
313                if !self.is_array() { return Err("xpath error-current is not array".into()); }
314                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
315                self[index].set_by_xpath(&xp[1..], value)?;
316            } else {
317                if !self.is_object() { return Err("xpath error-current is not object".into()); }
318                self[xp[0].as_str()].set_by_xpath(&xp[1..], value)?;
319            };
320        } else {
321            *self = value;
322        }
323        Ok(())
324    }
325
326    pub fn set_value_by_xpath<T: Into<JsonValue>>(&mut self, xpath: &str, other: T) -> JsonResult<()> {
327        let paths = xpath.split('.').collect::<Vec<_>>();
328        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
329        self.set_by_xpath(xpaths.as_slice(), other.into())?;
330        Ok(())
331    }
332
333    fn get_by_xpath(&self, xp: &[String]) -> JsonResult<&JsonValue> {
334        if xp.len() != 0 {
335            if xp[0].starts_with("[") && xp[0].ends_with("]") {
336                if !self.is_array() { return Err("xpath error-current is not array".into()); }
337                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
338                self[index].get_by_xpath(&xp[1..])
339            } else {
340                if !self.is_object() { return Err("xpath error-current is not object".into()); }
341                self[xp[0].as_str()].get_by_xpath(&xp[1..])
342            }
343        } else {
344            Ok(self)
345        }
346    }
347
348    pub fn xpath(&self, xpath: &str) -> JsonResult<&JsonValue> {
349        let paths = xpath.split('.').collect::<Vec<_>>();
350        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
351        self.get_by_xpath(xpaths.as_slice())
352    }
353
354    fn remove_by_xpath(&mut self, xp: &[String]) -> JsonResult<JsonValue> {
355        if xp.len() == 1 {
356            if xp[0].starts_with("[") && xp[0].ends_with("]") {
357                if !self.is_array() { return Err("xpath error-current is not array".into()); }
358                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
359                Ok(self.array_remove(index))
360            } else {
361                if !self.is_object() { return Err("xpath error-current is not object".into()); }
362                Ok(self.remove(xp[0].as_str()))
363            }
364        } else {
365            if xp[0].starts_with("[") && xp[0].ends_with("]") {
366                if !self.is_array() { return Err("xpath error-current is not array".into()); }
367                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
368                self[index].remove_by_xpath(&xp[1..])
369            } else {
370                if !self.is_object() { return Err("xpath error-current is not object".into()); }
371                self[xp[0].as_str()].remove_by_xpath(&xp[1..])
372            }
373        }
374    }
375
376    pub fn remove_value_by_xpath(&mut self, xpath: &str) -> JsonResult<JsonValue> {
377        let paths = xpath.split('.').collect::<Vec<_>>();
378        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
379        if xpaths.len() == 0 { return Err("xpath error".into()); }
380        self.remove_by_xpath(xpaths.as_slice())
381    }
382
383    pub fn into_key(mut self, key: impl AsRef<str>) -> JsonValue {
384        self.remove(key.as_ref())
385    }
386
387    pub fn into_index(mut self, index: usize) -> JsonValue {
388        self.array_remove(index)
389    }
390}
391
392impl Debug for JsonValue {
393    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
394        f.write_str(self.dump().as_str())
395    }
396}
397
398unsafe impl Send for JsonValue {}
399
400
401/// ```
402/// # #[macro_use] extern crate json;
403/// # fn main() {
404/// let data = array!["foo", 42, false];
405/// # }
406/// ```
407#[macro_export]
408macro_rules! array {
409    [] => ($crate::JsonValue::new_array());
410
411    // Handles for token tree items
412    [@ITEM($( $i:expr, )*) $item:tt, $( $cont:tt )+] => {
413        $crate::array!(
414            @ITEM($( $i, )* $crate::value!($item), )
415            $( $cont )*
416        )
417    };
418    (@ITEM($( $i:expr, )*) $item:tt,) => ({
419        $crate::array!(@END $( $i, )* $crate::value!($item), )
420    });
421    (@ITEM($( $i:expr, )*) $item:tt) => ({
422        $crate::array!(@END $( $i, )* $crate::value!($item), )
423    });
424
425    // Handles for expression items
426    [@ITEM($( $i:expr, )*) $item:expr, $( $cont:tt )+] => {
427        $crate::array!(
428            @ITEM($( $i, )* $crate::value!($item), )
429            $( $cont )*
430        )
431    };
432    (@ITEM($( $i:expr, )*) $item:expr,) => ({
433        $crate::array!(@END $( $i, )* $crate::value!($item), )
434    });
435    (@ITEM($( $i:expr, )*) $item:expr) => ({
436        $crate::array!(@END $( $i, )* $crate::value!($item), )
437    });
438
439    // Construct the actual array
440    (@END $( $i:expr, )*) => ({
441        let size = 0 $( + {let _ = &$i; 1} )*;
442        let mut array = Vec::with_capacity(size);
443
444        $(
445            array.push($i.into());
446        )*
447
448        $crate::JsonValue::Array(array)
449    });
450
451    // Entry point to the macro
452    ($( $cont:tt )+) => {
453        $crate::array!(@ITEM() $($cont)*)
454    };
455}
456
457#[macro_export]
458/// Helper crate for converting types into `JsonValue`. It's used
459/// internally by the `object!` and `array!` macros.
460macro_rules! value {
461    ( null ) => { $crate::JsonValue::Null };
462    ( [$( $token:tt )*] ) => {
463        // 10
464        $crate::array![ $( $token )* ]
465    };
466    ( {$( $token:tt )*} ) => {
467        $crate::object!{ $( $token )* }
468    };
469    { $value:expr } => { $value };
470}
471
472/// Helper macro for creating instances of `JsonValue::Object`.
473///
474/// ```
475/// # #[macro_use] extern crate json;
476/// # fn main() {
477/// let data = object!{
478///     foo: 42,
479///     bar: false,
480/// };
481/// # }
482/// ```
483#[macro_export]
484macro_rules! object {
485    // Empty object.
486    {} => ($crate::JsonValue::new_object());
487
488    // Handles for different types of keys
489    (@ENTRY($( $k:expr => $v:expr, )*) $key:ident: $( $cont:tt )*) => {
490        $crate::object!(@ENTRY($( $k => $v, )*) stringify!($key) => $($cont)*)
491    };
492    (@ENTRY($( $k:expr => $v:expr, )*) $key:literal: $( $cont:tt )*) => {
493        $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
494    };
495    (@ENTRY($( $k:expr => $v:expr, )*) [$key:expr]: $( $cont:tt )*) => {
496        $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
497    };
498
499    // Handles for token tree values
500    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt, $( $cont:tt )+) => {
501        $crate::object!(
502            @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
503            $( $cont )*
504        )
505    };
506    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt,) => ({
507        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
508    });
509    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt) => ({
510        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
511    });
512
513    // Handles for expression values
514    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr, $( $cont:tt )+) => {
515        $crate::object!(
516            @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
517            $( $cont )*
518        )
519    };
520    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr,) => ({
521        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
522    });
523
524    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr) => ({
525        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
526    });
527
528    // Construct the actual object
529    (@END $( $k:expr => $v:expr, )*) => ({
530        // let size = 0 $( + {let _ = &$k; 1} )*;
531        let mut object = $crate::JsonValue::new_object();
532
533
534        $(
535            let s=$crate::JsonValue::from($v);
536            object.insert($k, s).unwrap();
537        )*
538        object
539        //$crat// e::JsonValue::Object(object)
540    });
541
542    // Entry point to the macro
543    ($key:tt: $( $cont:tt )+) => {
544        $crate::object!(@ENTRY() $key: $($cont)*)
545    };
546
547    // Legacy macro
548    ($( $k:expr => $v:expr, )*) => {
549        $crate::object!(@END $( $k => $crate::value!($v), )*)
550    };
551    ($( $k:expr => $v:expr ),*) => {
552        $crate::object!(@END $( $k => $crate::value!($v), )*)
553    };
554}
555
556
557
558
559