use indexmap::IndexMap;
use std::{borrow::Cow, fmt::Debug, rc::Rc};
pub type ValueMap<'a> = IndexMap<String, Value<'a>>;
pub trait Object<'a>: Debug {
fn type_name(&self) -> &'static str;
fn as_any(&self) -> Option<&dyn std::any::Any> {
None
}
fn underlying(&self) -> Option<&Value<'a>> {
None
}
fn field(&self, _name: &str) -> Option<Value<'a>> {
None
}
fn method(
&self,
_name: &str,
_args: Vec<Arg<'a, '_>>,
) -> Option<crate::error::Result<Value<'a>>> {
None
}
fn call(&self, _args: &[Value<'a>]) -> Option<crate::error::Result<Value<'a>>> {
None
}
fn is_callable(&self) -> bool {
false
}
fn display(&self) -> crate::error::Result<String> {
Err(crate::error::Error::new(
crate::error::ErrorKind::Render,
format!("{} cannot be printed", self.type_name()),
None,
))
}
fn display_text(&self) -> Option<&str> {
None
}
fn is_trusted_html(&self) -> bool {
false
}
fn entries(&self, _limit: usize) -> crate::error::Result<Vec<(Value<'a>, Value<'a>)>> {
Err(crate::error::Error::new(
crate::error::ErrorKind::Render,
format!("cannot iterate {}", self.type_name()),
None,
))
}
fn json_kind(&self) -> crate::encode::JsonKind<'_> {
crate::encode::JsonKind::Null
}
}
#[derive(Clone, Debug)]
pub enum Value<'a> {
Null,
Bool(bool),
Int(i64),
Float(f64),
Str(Cow<'a, str>),
Html(Cow<'a, str>),
Json(&'a serde_json::Value),
List(Vec<Value<'a>>),
Map(ValueMap<'a>),
Object(Rc<dyn Object<'a> + 'a>),
}
impl<'a> Value<'a> {
pub fn string(text: impl Into<Cow<'a, str>>) -> Self {
Self::Str(text.into())
}
pub fn html(text: impl Into<Cow<'a, str>>) -> Self {
Self::Html(text.into())
}
pub fn object(object: impl Object<'a> + 'a) -> Self {
Self::Object(Rc::new(object))
}
}
pub(crate) fn owned_data_depth_error() -> crate::error::Error {
crate::error::Error::new(
crate::error::ErrorKind::Limit,
"owned render data depth limit exceeded",
None,
)
}
impl Value<'_> {
pub(crate) fn owned_depth_within(&self, remaining: usize) -> bool {
match self {
Self::List(items) => {
remaining > 0
&& items
.iter()
.all(|value| value.owned_depth_within(remaining - 1))
}
Self::Map(fields) => {
remaining > 0
&& fields
.values()
.all(|value| value.owned_depth_within(remaining - 1))
}
_ => true,
}
}
pub(crate) fn discard_deep_owned(self) {
let mut pending = vec![self];
while let Some(value) = pending.pop() {
match value {
Self::List(items) => pending.extend(items),
Self::Map(fields) => pending.extend(fields.into_values()),
_ => {}
}
}
}
}
pub(crate) const MAX_OWNED_DATA_DEPTH: usize = 128;
#[derive(Debug)]
struct RejectedOwnedData;
impl Object<'_> for RejectedOwnedData {
fn type_name(&self) -> &'static str {
"rejected owned render data"
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
Some(self)
}
fn display(&self) -> crate::error::Result<String> {
Err(owned_data_depth_error())
}
}
impl<'a> Value<'a> {
pub(crate) fn is_rejected_owned_data(&self) -> bool {
matches!(self, Self::Object(object) if object.as_any().is_some_and(|object| object.is::<RejectedOwnedData>()))
}
pub(crate) fn reject_if_too_deep(&mut self) {
if !self.owned_depth_within(MAX_OWNED_DATA_DEPTH) {
std::mem::replace(self, Self::object(RejectedOwnedData)).discard_deep_owned();
}
}
pub(crate) fn clone_with_depth_bound(&self) -> Self {
if self.owned_depth_within(MAX_OWNED_DATA_DEPTH) {
self.clone()
} else {
Self::object(RejectedOwnedData)
}
}
}
pub(crate) fn check_owned_layer(layer: ValueMap<'_>) -> crate::error::Result<ValueMap<'_>> {
if layer
.values()
.all(|value| value.owned_depth_within(MAX_OWNED_DATA_DEPTH))
{
return Ok(layer);
}
Value::Map(layer).discard_deep_owned();
Err(owned_data_depth_error())
}
pub(crate) fn bound_owned_layer(layer: &mut ValueMap<'_>) {
layer.values_mut().for_each(Value::reject_if_too_deep);
}
pub(crate) fn bounded_owned_layers<'a>(
layers: impl IntoIterator<Item = ValueMap<'a>>,
) -> impl Iterator<Item = ValueMap<'a>> {
let mut layers = layers.into_iter();
let mut first = layers.next();
if let Some(first) = &mut first {
bound_owned_layer(first);
}
let rest = layers
.map(|mut layer| {
bound_owned_layer(&mut layer);
layer
})
.collect::<Vec<_>>();
first.into_iter().chain(rest)
}
pub trait Callable<'a> {
fn call(&mut self, args: &[Value<'a>]) -> crate::error::Result<Value<'a>>;
}
pub enum Arg<'a, 'c> {
Value(Value<'a>),
Closure(&'c mut dyn Callable<'a>),
}
impl<'a> Value<'a> {
pub fn scalar(&self) -> Self {
match self {
Self::Json(serde_json::Value::Null) => Self::Null,
Self::Json(serde_json::Value::Bool(value)) => Self::Bool(*value),
Self::Json(serde_json::Value::Number(value)) => value.as_i64().map_or_else(
|| Self::Float(value.as_f64().unwrap_or(f64::INFINITY)),
Self::Int,
),
Self::Json(serde_json::Value::String(value)) => Self::string(value.as_str()),
Self::Object(object) => object
.underlying()
.map_or_else(|| self.clone(), Self::scalar),
value => value.clone(),
}
}
pub fn type_name(&self) -> &'static str {
match self {
Self::Null | Self::Json(serde_json::Value::Null) => "None",
Self::Bool(_) | Self::Json(serde_json::Value::Bool(_)) => "bool",
Self::Int(_) => "i64",
Self::Float(_) => "f64",
Self::Str(_) | Self::Json(serde_json::Value::String(_)) => "string",
Self::Html(_) => "HTML",
Self::List(_) | Self::Json(serde_json::Value::Array(_)) => "list",
Self::Map(_) | Self::Json(serde_json::Value::Object(_)) => "map",
Self::Object(object) => object.type_name(),
Self::Json(serde_json::Value::Number(number)) if number.is_i64() => "i64",
Self::Json(serde_json::Value::Number(_)) => "f64",
}
}
pub fn is_null(&self) -> bool {
match self {
Self::Object(object) => object.underlying().is_some_and(Self::is_null),
value => matches!(value, Self::Null | Self::Json(serde_json::Value::Null)),
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Str(value) => Some(value),
Self::Json(value) => value.as_str(),
Self::Object(object) => object.underlying()?.as_str(),
_ => None,
}
}
pub fn field(&self, name: &str) -> Option<Self> {
match self {
Self::Map(fields) => fields.get(name).cloned(),
Self::Json(serde_json::Value::Object(fields)) => fields.get(name).map(Self::Json),
Self::Object(object) => object.field(name),
_ => None,
}
}
pub fn display(&self) -> crate::error::Result<String> {
Ok(match self {
Self::Str(value) | Self::Html(value) => value.to_string(),
Self::Bool(value) => value.to_string(),
Self::Int(value) => value.to_string(),
Self::Float(value) => value.to_string(),
Self::Null => String::new(),
Self::Json(value) if !value.is_array() && !value.is_object() => {
return self.scalar().display();
}
Self::Object(object) => return object.display(),
_ => {
return Err(crate::error::Error::new(
crate::error::ErrorKind::Render,
format!("{} cannot be printed", self.type_name()),
None,
));
}
})
}
pub fn is_trusted_html(&self) -> bool {
match self {
Self::Html(_) => true,
Self::Object(object) => object.is_trusted_html(),
_ => false,
}
}
pub fn entries(&self, limit: usize) -> crate::error::Result<Vec<(Self, Self)>> {
let size = match self {
Self::List(values) => values.len(),
Self::Map(values) => values.len(),
Self::Json(serde_json::Value::Array(values)) => values.len(),
Self::Json(serde_json::Value::Object(values)) => values.len(),
Self::Object(object) => return object.entries(limit),
_ => {
return Err(crate::error::Error::new(
crate::error::ErrorKind::Render,
format!("cannot iterate {}", self.type_name()),
None,
));
}
};
if size > limit {
return Err(expansion_error());
}
let indexed = |(index, value)| (Self::Int(index as i64), value);
Ok(match self {
Self::List(values) => values.iter().cloned().enumerate().map(indexed).collect(),
Self::Map(values) => values
.iter()
.map(|(key, value)| (Self::string(key.clone()), value.clone()))
.collect(),
Self::Json(serde_json::Value::Array(values)) => values
.iter()
.map(Self::Json)
.enumerate()
.map(indexed)
.collect(),
Self::Json(serde_json::Value::Object(values)) => values
.iter()
.map(|(key, value)| (Self::string(key.as_str()), Self::Json(value)))
.collect(),
_ => Vec::new(),
})
}
}
pub(crate) fn expansion_error() -> crate::error::Error {
crate::error::Error::new(
crate::error::ErrorKind::Limit,
"collection expansion limit exceeded",
None,
)
}
impl crate::encode::JsonValue for Value<'_> {
fn json_kind(&self) -> crate::encode::JsonKind<'_> {
use crate::encode::{ArrayKey, JsonKind, JsonValue};
match self {
Self::Null => JsonKind::Null,
Self::Bool(value) => JsonKind::Bool(*value),
Self::Int(value) => JsonKind::Integer(*value),
Self::Float(value) => JsonKind::Float(*value),
Self::Str(value) | Self::Html(value) => JsonKind::String(value.as_bytes()),
Self::Json(value) => value.json_kind(),
Self::List(values) => {
JsonKind::Array(Box::new(values.iter().zip(0..).map(|(value, index)| {
(ArrayKey::Integer(index), value as &dyn JsonValue)
})))
}
Self::Map(values) => {
JsonKind::Array(Box::new(values.iter().map(|(key, value)| {
(ArrayKey::from(key.as_str()), value as &dyn JsonValue)
})))
}
Self::Object(object) => object.json_kind(),
}
}
}