facet_json/
raw_json.rs

1//! Raw JSON value that defers parsing.
2//!
3//! [`RawJson`] captures unparsed JSON text, allowing you to delay or skip
4//! deserialization of parts of a JSON document.
5
6use alloc::borrow::Cow;
7use alloc::string::String;
8use core::fmt;
9use facet::Facet;
10
11/// A raw JSON value that has not been parsed.
12///
13/// This type captures the raw JSON text for a value, deferring parsing until
14/// you're ready (or skipping it entirely if you just need to pass it through).
15///
16/// # Example
17///
18/// ```
19/// use facet::Facet;
20/// use facet_json::RawJson;
21///
22/// #[derive(Facet, Debug)]
23/// struct Response<'a> {
24///     status: u32,
25///     // We don't know what shape `data` has, so defer parsing
26///     data: RawJson<'a>,
27/// }
28///
29/// let json = r#"{"status": 200, "data": {"nested": [1, 2, 3], "complex": true}}"#;
30/// let response: Response = facet_json::from_str_borrowed(json).unwrap();
31///
32/// assert_eq!(response.status, 200);
33/// assert_eq!(response.data.as_str(), r#"{"nested": [1, 2, 3], "complex": true}"#);
34/// ```
35#[derive(Clone, PartialEq, Eq, Hash, Facet)]
36pub struct RawJson<'a>(pub Cow<'a, str>);
37
38impl<'a> RawJson<'a> {
39    /// Create a new `RawJson` from a string slice.
40    #[inline]
41    pub fn new(s: &'a str) -> Self {
42        RawJson(Cow::Borrowed(s))
43    }
44
45    /// Create a new `RawJson` from an owned string.
46    #[inline]
47    pub fn from_owned(s: String) -> Self {
48        RawJson(Cow::Owned(s))
49    }
50
51    /// Get the raw JSON as a string slice.
52    #[inline]
53    pub fn as_str(&self) -> &str {
54        &self.0
55    }
56
57    /// Convert into an owned `RawJson<'static>`.
58    #[inline]
59    pub fn into_owned(self) -> RawJson<'static> {
60        RawJson(Cow::Owned(self.0.into_owned()))
61    }
62}
63
64impl fmt::Debug for RawJson<'_> {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_tuple("RawJson").field(&self.0).finish()
67    }
68}
69
70impl fmt::Display for RawJson<'_> {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(&self.0)
73    }
74}
75
76impl<'a> From<&'a str> for RawJson<'a> {
77    fn from(s: &'a str) -> Self {
78        RawJson::new(s)
79    }
80}
81
82impl<'a> From<Cow<'a, str>> for RawJson<'a> {
83    fn from(s: Cow<'a, str>) -> Self {
84        RawJson(s)
85    }
86}
87
88impl From<String> for RawJson<'static> {
89    fn from(s: String) -> Self {
90        RawJson::from_owned(s)
91    }
92}
93
94impl<'a> AsRef<str> for RawJson<'a> {
95    fn as_ref(&self) -> &str {
96        self.as_str()
97    }
98}