use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::Error;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged, expecting = "a string, an object or an array")]
pub enum Content {
Text(String),
Object(Map<String, Value>),
Array(Vec<Value>),
}
impl Content {
pub fn as_str(&self) -> Option<&str> {
match self {
Content::Text(text) => Some(text),
Content::Object(_) | Content::Array(_) => None,
}
}
}
impl From<&str> for Content {
fn from(text: &str) -> Self {
Content::Text(text.to_owned())
}
}
impl From<String> for Content {
fn from(text: String) -> Self {
Content::Text(text)
}
}
impl From<&String> for Content {
fn from(text: &String) -> Self {
Content::Text(text.clone())
}
}
impl From<Map<String, Value>> for Content {
fn from(object: Map<String, Value>) -> Self {
Content::Object(object)
}
}
impl From<Vec<Value>> for Content {
fn from(array: Vec<Value>) -> Self {
Content::Array(array)
}
}
impl TryFrom<Value> for Content {
type Error = Error;
fn try_from(value: Value) -> Result<Self, Error> {
match value {
Value::String(text) => Ok(Content::Text(text)),
Value::Object(object) => Ok(Content::Object(object)),
Value::Array(array) => Ok(Content::Array(array)),
Value::Null | Value::Bool(_) | Value::Number(_) => {
Err(Error::InvalidRequest("content must be a string, an object or an array".into()))
}
}
}
}
impl From<Content> for Value {
fn from(content: Content) -> Self {
match content {
Content::Text(text) => Value::String(text),
Content::Object(object) => Value::Object(object),
Content::Array(array) => Value::Array(array),
}
}
}