facet_json/
json.rs

1//! The `Json<T>` wrapper type for JSON serialization/deserialization.
2
3use core::fmt;
4use core::ops::{Deref, DerefMut};
5
6/// A wrapper type for JSON serialization and deserialization.
7///
8/// This type can be used standalone for convenient JSON operations,
9/// and when the `axum` feature is enabled, it implements Axum's
10/// `FromRequest` and `IntoResponse` traits.
11///
12/// # Example
13///
14/// ```
15/// use facet::Facet;
16/// use facet_json::Json;
17///
18/// #[derive(Debug, Facet)]
19/// struct User {
20///     name: String,
21///     age: u32,
22/// }
23///
24/// // Wrap a value
25/// let user = Json(User { name: "Alice".to_string(), age: 30 });
26///
27/// // Access the inner value
28/// println!("Name: {}", user.name);
29/// ```
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Json<T>(pub T);
32
33impl<T> Json<T> {
34    /// Consume the wrapper and return the inner value.
35    #[inline]
36    pub fn into_inner(self) -> T {
37        self.0
38    }
39}
40
41impl<T> From<T> for Json<T> {
42    #[inline]
43    fn from(inner: T) -> Self {
44        Json(inner)
45    }
46}
47
48impl<T> Deref for Json<T> {
49    type Target = T;
50
51    #[inline]
52    fn deref(&self) -> &Self::Target {
53        &self.0
54    }
55}
56
57impl<T> DerefMut for Json<T> {
58    #[inline]
59    fn deref_mut(&mut self) -> &mut Self::Target {
60        &mut self.0
61    }
62}
63
64impl<T> AsRef<T> for Json<T> {
65    #[inline]
66    fn as_ref(&self) -> &T {
67        &self.0
68    }
69}
70
71impl<T> AsMut<T> for Json<T> {
72    #[inline]
73    fn as_mut(&mut self) -> &mut T {
74        &mut self.0
75    }
76}
77
78impl<T: fmt::Display> fmt::Display for Json<T> {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        self.0.fmt(f)
81    }
82}