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 insert<T>(&mut self, key: &str, value: T) -> JsonResult<()>
160    where
161        T: Into<JsonValue>,
162    {
163        match self {
164            JsonValue::Object(o) => { Ok(o.insert(key, value.into())) }
165            _ => Err("Wrong Type Object!".into())
166        }
167    }
168
169    pub fn pretty(&self) -> String {
170        match self {
171            JsonValue::Null => "null".to_string(),
172            JsonValue::String(v) => v.clone(),
173            _ => to_string_pretty(self).unwrap()
174        }
175    }
176
177    pub fn dump(&self) -> String {
178        match self {
179            JsonValue::Null => "null".to_string(),
180            JsonValue::String(v) => v.clone(),
181            _ => to_string(self).unwrap()
182        }
183    }
184
185    pub fn has_key(&self, key: &str) -> bool {
186        match *self {
187            JsonValue::Object(ref object) => !object.get(key).is_null(),
188            _ => false
189        }
190    }
191
192    pub fn members(&self) -> Iter<'_, JsonValue> {
193        match self {
194            JsonValue::Array(vec) => vec.iter(),
195            _ => [].iter()
196        }
197    }
198
199    pub fn members_mut(&mut self) -> IterMut<'_, JsonValue> {
200        match self {
201            JsonValue::Array(vec) => vec.iter_mut(),
202            _ => [].iter_mut()
203        }
204    }
205
206    pub fn into_members(self) -> IntoIter<JsonValue> {
207        match self {
208            JsonValue::Array(vec) => vec.into_iter(),
209            _ => vec![].into_iter()
210        }
211    }
212
213    pub fn entries(&self) -> ObjectIter<'_> {
214        match self {
215            JsonValue::Object(object) => object.iter(),
216            _ => ObjectIter::empty()
217        }
218    }
219
220    pub fn entries_mut(&mut self) -> ObjectIterMut<'_> {
221        match self {
222            JsonValue::Object(object) => object.iter_mut(),
223            _ => ObjectIterMut::empty()
224        }
225    }
226
227    pub fn into_entries(self) -> ObjectIntoIter {
228        match self {
229            JsonValue::Object(object) => object.into_iter(),
230            _ => ObjectIntoIter::empty()
231        }
232    }
233
234    pub fn clear(&mut self) {
235        match self {
236            JsonValue::String(string) => string.clear(),
237            JsonValue::Object(object) => object.clear(),
238            JsonValue::Array(vec) => vec.clear(),
239            _ => *self = JsonValue::Null,
240        }
241    }
242
243    pub fn remove(&mut self, key: &str) -> JsonValue {
244        match self {
245            JsonValue::Object(object) => object.remove(key),
246            _ => JsonValue::Null,
247        }
248    }
249
250    pub fn array_remove(&mut self, index: usize) -> JsonValue {
251        match self {
252            JsonValue::Array(array) => { array.remove(index) }
253            _ => JsonValue::Null
254        }
255    }
256
257    /// must update_first
258    pub fn as_struct<T: for<'a> Deserialize<'a>>(&self) -> JsonResult<T> {
259        let s = self.dump();
260        Ok(serde_json::from_str(s.as_str())?)
261    }
262
263    pub fn write_file(&self, fp: impl AsRef<Path>) -> JsonResult<()> {
264        std::fs::write(fp.as_ref(), self.pretty())?;
265        Ok(())
266    }
267
268    fn update(json1: &mut JsonValue, json2: JsonValue) -> JsonResult<()> {
269        for (k, v) in json2.entries() {
270            if v.is_object() && json1.has_key(k) {
271                if json1[k].is_null() {
272                    json1[k] = JsonValue::new_object();
273                }
274                if !json1[k].is_object() {
275                    json1[k] = JsonValue::new_object();
276                }
277                Self::update(&mut json1[k], json2[k].clone())?;
278                continue;
279            } else if v.is_object() && !json1.has_key(k) {
280                if json1[k].is_null() {
281                    json1[k] = JsonValue::new_array()
282                }
283                if !json1[k].is_array() {
284                    json1[k] = JsonValue::new_array();
285                }
286                json1.insert(k, json2[k].clone())?;
287                continue;
288            }
289            json1.insert(k, json2[k].clone())?;
290        }
291        Ok(())
292    }
293
294    pub fn update_by(&mut self, other: JsonValue) -> JsonResult<()> {
295        Self::update(self, other)
296    }
297
298    fn set_by_xpath(&mut self, xp: &[String], value: JsonValue) -> JsonResult<()> {
299        if !xp.is_empty() {
300            if xp[0].starts_with("[") && xp[0].ends_with("]") {
301                if !self.is_array() { return Err("xpath error-current is not array".into()); }
302                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
303                self[index].set_by_xpath(&xp[1..], value)?;
304            } else {
305                if !self.is_object() { return Err("xpath error-current is not object".into()); }
306                self[xp[0].as_str()].set_by_xpath(&xp[1..], value)?;
307            };
308        } else {
309            *self = value;
310        }
311        Ok(())
312    }
313
314    pub fn set_value_by_xpath<T: Into<JsonValue>>(&mut self, xpath: &str, other: T) -> JsonResult<()> {
315        let paths = xpath.split('.').collect::<Vec<_>>();
316        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
317        self.set_by_xpath(xpaths.as_slice(), other.into())?;
318        Ok(())
319    }
320
321    fn get_by_xpath(&self, xp: &[String]) -> JsonResult<&JsonValue> {
322        if xp.len() != 0 {
323            if xp[0].starts_with("[") && xp[0].ends_with("]") {
324                if !self.is_array() { return Err("xpath error-current is not array".into()); }
325                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
326                self[index].get_by_xpath(&xp[1..])
327            } else {
328                if !self.is_object() { return Err("xpath error-current is not object".into()); }
329                self[xp[0].as_str()].get_by_xpath(&xp[1..])
330            }
331        } else {
332            Ok(self)
333        }
334    }
335
336    pub fn xpath(&self, xpath: &str) -> JsonResult<&JsonValue> {
337        let paths = xpath.split('.').collect::<Vec<_>>();
338        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
339        self.get_by_xpath(xpaths.as_slice())
340    }
341
342    fn remove_by_xpath(&mut self, xp: &[String]) -> JsonResult<JsonValue> {
343        if xp.len() == 1 {
344            if xp[0].starts_with("[") && xp[0].ends_with("]") {
345                if !self.is_array() { return Err("xpath error-current is not array".into()); }
346                let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
347                Ok(self.array_remove(index))
348            } else {
349                if !self.is_object() { return Err("xpath error-current is not object".into()); }
350                Ok(self.remove(xp[0].as_str()))
351            }
352        } else if xp[0].starts_with("[") && xp[0].ends_with("]") {
353            if !self.is_array() { return Err("xpath error-current is not array".into()); }
354            let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
355            self[index].remove_by_xpath(&xp[1..])
356        } else {
357            if !self.is_object() { return Err("xpath error-current is not object".into()); }
358            self[xp[0].as_str()].remove_by_xpath(&xp[1..])
359        }
360    }
361
362    pub fn remove_value_by_xpath(&mut self, xpath: &str) -> JsonResult<JsonValue> {
363        let paths = xpath.split('.').collect::<Vec<_>>();
364        let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
365        if xpaths.is_empty() { return Err("xpath error".into()); }
366        self.remove_by_xpath(xpaths.as_slice())
367    }
368
369    pub fn into_key(mut self, key: impl AsRef<str>) -> JsonValue {
370        self.remove(key.as_ref())
371    }
372
373    pub fn into_index(mut self, index: usize) -> JsonValue {
374        self.array_remove(index)
375    }
376}
377
378impl Debug for JsonValue {
379    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
380        f.write_str(self.dump().as_str())
381    }
382}
383
384unsafe impl Send for JsonValue {}
385
386
387/// ```
388/// # use reqrio_json as json;
389/// # fn main() {
390/// let data = json::array!["foo", 42, false];
391/// # }
392/// ```
393#[macro_export]
394macro_rules! array {
395    [] => ($crate::JsonValue::new_array());
396
397    // Handles for token tree items
398    [@ITEM($( $i:expr, )*) $item:tt, $( $cont:tt )+] => {
399        $crate::array!(
400            @ITEM($( $i, )* $crate::value!($item), )
401            $( $cont )*
402        )
403    };
404    (@ITEM($( $i:expr, )*) $item:tt,) => ({
405        $crate::array!(@END $( $i, )* $crate::value!($item), )
406    });
407    (@ITEM($( $i:expr, )*) $item:tt) => ({
408        $crate::array!(@END $( $i, )* $crate::value!($item), )
409    });
410
411    // Handles for expression items
412    [@ITEM($( $i:expr, )*) $item:expr, $( $cont:tt )+] => {
413        $crate::array!(
414            @ITEM($( $i, )* $crate::value!($item), )
415            $( $cont )*
416        )
417    };
418    (@ITEM($( $i:expr, )*) $item:expr,) => ({
419        $crate::array!(@END $( $i, )* $crate::value!($item), )
420    });
421    (@ITEM($( $i:expr, )*) $item:expr) => ({
422        $crate::array!(@END $( $i, )* $crate::value!($item), )
423    });
424
425    // Construct the actual array
426    (@END $( $i:expr, )*) => ({
427        let size = 0 $( + {let _ = &$i; 1} )*;
428        let mut array = Vec::with_capacity(size);
429
430        $(
431            array.push($i.into());
432        )*
433
434        $crate::JsonValue::Array(array)
435    });
436
437    // Entry point to the macro
438    ($( $cont:tt )+) => {
439        $crate::array!(@ITEM() $($cont)*)
440    };
441}
442
443#[macro_export]
444/// Helper crate for converting types into `JsonValue`. It's used
445/// internally by the `object!` and `array!` macros.
446macro_rules! value {
447    ( null ) => { $crate::JsonValue::Null };
448    ( [$( $token:tt )*] ) => {
449        // 10
450        $crate::array![ $( $token )* ]
451    };
452    ( {$( $token:tt )*} ) => {
453        $crate::object!{ $( $token )* }
454    };
455    { $value:expr } => { $value };
456}
457
458/// Helper macro for creating instances of `JsonValue::Object`.
459///
460/// ```
461/// # use reqrio_json as json;
462/// # fn main() {
463/// let data = json::object!{
464///     foo: 42,
465///     bar: false,
466/// };
467/// # }
468/// ```
469#[macro_export]
470macro_rules! object {
471    // Empty object.
472    {} => ($crate::JsonValue::new_object());
473
474    // Handles for different types of keys
475    (@ENTRY($( $k:expr => $v:expr, )*) $key:ident: $( $cont:tt )*) => {
476        $crate::object!(@ENTRY($( $k => $v, )*) stringify!($key) => $($cont)*)
477    };
478    (@ENTRY($( $k:expr => $v:expr, )*) $key:literal: $( $cont:tt )*) => {
479        $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
480    };
481    (@ENTRY($( $k:expr => $v:expr, )*) [$key:expr]: $( $cont:tt )*) => {
482        $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
483    };
484
485    // Handles for token tree values
486    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt, $( $cont:tt )+) => {
487        $crate::object!(
488            @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
489            $( $cont )*
490        )
491    };
492    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt,) => ({
493        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
494    });
495    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt) => ({
496        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
497    });
498
499    // Handles for expression values
500    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr, $( $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:expr,) => ({
507        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
508    });
509
510    (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr) => ({
511        $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
512    });
513
514    // Construct the actual object
515    (@END $( $k:expr => $v:expr, )*) => ({
516        // let size = 0 $( + {let _ = &$k; 1} )*;
517        let mut object = $crate::JsonValue::new_object();
518
519
520        $(
521            let s=$crate::JsonValue::from($v);
522            object.insert($k, s).unwrap();
523        )*
524        object
525        //$crat// e::JsonValue::Object(object)
526    });
527
528    // Entry point to the macro
529    ($key:tt: $( $cont:tt )+) => {
530        $crate::object!(@ENTRY() $key: $($cont)*)
531    };
532
533    // Legacy macro
534    ($( $k:expr => $v:expr, )*) => {
535        $crate::object!(@END $( $k => $crate::value!($v), )*)
536    };
537    ($( $k:expr => $v:expr ),*) => {
538        $crate::object!(@END $( $k => $crate::value!($v), )*)
539    };
540}
541
542
543
544
545