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