use std::borrow::Cow;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Content(Value);
impl Content {
#[must_use]
pub const fn null() -> Self {
Self(Value::Null)
}
#[must_use]
pub fn is_null(&self) -> bool {
self.0.is_null()
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
self.0.as_str()
}
#[must_use]
pub const fn as_value(&self) -> &Value {
&self.0
}
#[must_use]
pub fn into_value(self) -> Value {
self.0
}
}
impl From<Value> for Content {
fn from(value: Value) -> Self {
Self(value)
}
}
impl From<Content> for Value {
fn from(content: Content) -> Self {
content.0
}
}
impl From<String> for Content {
fn from(text: String) -> Self {
Self(Value::String(text))
}
}
impl From<&str> for Content {
fn from(text: &str) -> Self {
Self(Value::String(text.to_owned()))
}
}
impl JsonSchema for Content {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"Content".into()
}
fn schema_id() -> Cow<'static, str> {
concat!(module_path!(), "::Content").into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "Free-form content: a string, an object, an array, or null.",
"type": ["string", "object", "array", "null"]
})
}
}
pub(crate) fn non_null_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "Free-form content: a string, an object, or an array.",
"type": ["string", "object", "array"]
})
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::Content;
#[test]
fn serialises_transparently_as_the_wrapped_value() {
let content = Content::from(json!({ "b": 1, "a": [true, null] }));
assert_eq!(
serde_json::to_string(&content).unwrap(),
r#"{"b":1,"a":[true,null]}"#
);
}
#[test]
fn accepts_scalars_so_that_validation_can_report_them() {
let content: Content = serde_json::from_str("42").unwrap();
assert_eq!(content.as_value(), &json!(42));
assert_eq!(content.as_str(), None);
}
#[test]
fn distinguishes_null_from_text() {
assert!(Content::null().is_null());
assert!(Content::default().is_null());
assert!(!Content::from("").is_null());
}
#[test]
fn converts_to_and_from_json_values() {
let value = json!(["a", { "k": "v" }]);
assert_eq!(Content::from(value.clone()).into_value(), value);
assert_eq!(serde_json::Value::from(Content::from("x")), json!("x"));
assert_eq!(Content::from(String::from("x")), Content::from("x"));
}
}