Skip to main content

reqrio_json/
lib.rs

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