1use std::borrow::Cow;
4
5use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct Content(Value);
32
33impl Content {
34 #[must_use]
36 pub const fn null() -> Self {
37 Self(Value::Null)
38 }
39
40 #[must_use]
42 pub fn is_null(&self) -> bool {
43 self.0.is_null()
44 }
45
46 #[must_use]
48 pub fn as_str(&self) -> Option<&str> {
49 self.0.as_str()
50 }
51
52 #[must_use]
54 pub const fn as_value(&self) -> &Value {
55 &self.0
56 }
57
58 #[must_use]
60 pub fn into_value(self) -> Value {
61 self.0
62 }
63}
64
65impl From<Value> for Content {
66 fn from(value: Value) -> Self {
67 Self(value)
68 }
69}
70
71impl From<Content> for Value {
72 fn from(content: Content) -> Self {
73 content.0
74 }
75}
76
77impl From<String> for Content {
78 fn from(text: String) -> Self {
79 Self(Value::String(text))
80 }
81}
82
83impl From<&str> for Content {
84 fn from(text: &str) -> Self {
85 Self(Value::String(text.to_owned()))
86 }
87}
88
89impl JsonSchema for Content {
90 fn inline_schema() -> bool {
91 true
92 }
93
94 fn schema_name() -> Cow<'static, str> {
95 "Content".into()
96 }
97
98 fn schema_id() -> Cow<'static, str> {
99 concat!(module_path!(), "::Content").into()
100 }
101
102 fn json_schema(_: &mut SchemaGenerator) -> Schema {
103 json_schema!({
104 "description": "Free-form content: a string, an object, an array, or null.",
105 "type": ["string", "object", "array", "null"]
106 })
107 }
108}
109
110pub(crate) fn non_null_schema(_: &mut SchemaGenerator) -> Schema {
115 json_schema!({
116 "description": "Free-form content: a string, an object, or an array.",
117 "type": ["string", "object", "array"]
118 })
119}
120
121#[cfg(test)]
122mod tests {
123 use serde_json::json;
124
125 use super::Content;
126
127 #[test]
128 fn serialises_transparently_as_the_wrapped_value() {
129 let content = Content::from(json!({ "b": 1, "a": [true, null] }));
130
131 assert_eq!(
132 serde_json::to_string(&content).unwrap(),
133 r#"{"b":1,"a":[true,null]}"#
134 );
135 }
136
137 #[test]
138 fn accepts_scalars_so_that_validation_can_report_them() {
139 let content: Content = serde_json::from_str("42").unwrap();
140
141 assert_eq!(content.as_value(), &json!(42));
142 assert_eq!(content.as_str(), None);
143 }
144
145 #[test]
146 fn distinguishes_null_from_text() {
147 assert!(Content::null().is_null());
148 assert!(Content::default().is_null());
149 assert!(!Content::from("").is_null());
150 }
151
152 #[test]
153 fn converts_to_and_from_json_values() {
154 let value = json!(["a", { "k": "v" }]);
155
156 assert_eq!(Content::from(value.clone()).into_value(), value);
157 assert_eq!(serde_json::Value::from(Content::from("x")), json!("x"));
158 assert_eq!(Content::from(String::from("x")), Content::from("x"));
159 }
160}