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
#[cfg(feature = "json")]
pub mod json {
    use std::fmt::{self, Display};

    use serde::Serialize;
    use serde_json::{to_writer, to_writer_pretty};

    use crate::helpers::io_fmt::IoFmt;

    #[derive(Clone, Copy)]
    pub struct Json<'a, T: Serialize>(pub &'a T);

    pub trait AsJson {
        fn __as_json(&self) -> Json<'_, Self>
        where
            Self: Serialize + Sized;
    }

    impl<S> AsJson for S {
        fn __as_json(&self) -> Json<'_, Self>
        where
            Self: Serialize + Sized,
        {
            Json(self)
        }
    }

    #[derive(Clone, Copy)]
    pub struct JsonPretty<'a, T: Serialize>(pub &'a T);

    pub trait AsJsonPretty {
        fn __as_json_pretty(&self) -> JsonPretty<'_, Self>
        where
            Self: Serialize + Sized;
    }

    impl<S> AsJsonPretty for S {
        fn __as_json_pretty(&self) -> JsonPretty<'_, Self>
        where
            Self: Serialize + Sized,
        {
            JsonPretty(self)
        }
    }

    impl<'a, S: Serialize> Display for Json<'a, S> {
        #[inline(always)]
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            to_writer(IoFmt::new(f), self.0).map_err(|_| fmt::Error)
        }
    }

    impl<'a, D: Serialize> Display for JsonPretty<'a, D> {
        #[inline(always)]
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            to_writer_pretty(IoFmt::new(f), self.0).map_err(|_| fmt::Error)
        }
    }
}
#[cfg(feature = "json")]
pub use self::json::*;