yarte_helpers/
at_helpers.rs

1#[cfg(feature = "json")]
2pub mod json {
3    use std::fmt::{self, Display};
4
5    use serde::Serialize;
6    use serde_json::{to_writer, to_writer_pretty};
7
8    use crate::helpers::io_fmt::IoFmt;
9
10    pub struct Json<'a, T>(pub &'a T);
11
12    impl<'a, T> Clone for Json<'a, T> {
13        fn clone(&self) -> Self {
14            Json(self.0)
15        }
16    }
17
18    impl<'a, T> Copy for Json<'a, T> {}
19
20    pub trait AsJson {
21        fn __as_json(&self) -> Json<'_, Self>
22        where
23            Self: Sized;
24    }
25
26    impl<S> AsJson for S {
27        fn __as_json(&self) -> Json<'_, Self>
28        where
29            Self: Sized,
30        {
31            Json(self)
32        }
33    }
34
35    pub struct JsonPretty<'a, T>(pub &'a T);
36
37    impl<'a, T> Clone for JsonPretty<'a, T> {
38        fn clone(&self) -> Self {
39            JsonPretty(self.0)
40        }
41    }
42
43    impl<'a, T> Copy for JsonPretty<'a, T> {}
44
45    pub trait AsJsonPretty {
46        fn __as_json_pretty(&self) -> JsonPretty<'_, Self>
47        where
48            Self: Sized;
49    }
50
51    impl<S> AsJsonPretty for S {
52        fn __as_json_pretty(&self) -> JsonPretty<'_, Self>
53        where
54            Self: Sized,
55        {
56            JsonPretty(self)
57        }
58    }
59
60    impl<'a, S: Serialize> Display for Json<'a, S> {
61        #[inline(always)]
62        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63            to_writer(IoFmt::new(f), self.0).map_err(|_| fmt::Error)
64        }
65    }
66
67    impl<'a, S: Serialize> Display for JsonPretty<'a, S> {
68        #[inline(always)]
69        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70            to_writer_pretty(IoFmt::new(f), self.0).map_err(|_| fmt::Error)
71        }
72    }
73}
74#[cfg(feature = "json")]
75pub use self::json::*;