use crate::config;
use crate::kind::Kind;
use crate::pattern::Pattern;
use bigdecimal::{BigDecimal, RoundingMode};
use laravel::time::civil::{Date, DateTime};
use serde_json::{Map, Number, Value};
use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Get,
Set,
}
pub use crate::error::CastError;
fn invalid(cast: &str, reason: impl Into<String>) -> CastError {
CastError::Invalid {
cast: cast.to_owned(),
reason: reason.into(),
}
}
fn split_arguments(spec: &str) -> (&str, Option<&str>) {
spec.split_once(':')
.map_or((spec, None), |(name, arguments)| (name, Some(arguments)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Aliases(BTreeMap<String, String>);
impl Default for Aliases {
fn default() -> Self {
Self::none()
.with("date", "DateCast")
.with("date_parsed", "DateCast:true")
.with("date_month_year", "DateCast:true,m/Y,m/Y")
.with("datetime", "DateTimeCast")
.with("immutable_datetime", "DateTimeCast")
.with("immutable_date", "DateCast")
}
}
impl Aliases {
#[must_use]
pub fn none() -> Self {
Self(BTreeMap::new())
}
#[must_use]
pub fn with(mut self, alias: impl Into<String>, cast: impl Into<String>) -> Self {
self.0.insert(alias.into(), cast.into());
self
}
fn resolve(&self, spec: &str) -> Result<String, CastError> {
let (name, arguments) = split_arguments(spec);
let alias = self.0.get(name);
let resolved = alias.map_or(name, String::as_str);
match arguments {
Some(_) if alias.is_some() && split_arguments(resolved).1.is_some() => Err(invalid(
spec,
format!("`{name}` stands for `{resolved}`, which has its arguments"),
)),
Some(arguments) => Ok(format!("{resolved}:{arguments}")),
None => Ok(resolved.to_owned()),
}
}
}
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait AttributeCast: fmt::Debug + Send + Sync {
fn get(&self, value: &Value) -> Result<Value, CastError>;
fn set(&self, value: &Value) -> Result<Value, CastError>;
fn set_async<'a>(&'a self, value: &'a Value) -> BoxFuture<'a, Result<Value, CastError>> {
Box::pin(std::future::ready(self.set(value)))
}
fn tidy(&self, value: Value) -> Value {
value
}
fn skips_empty(&self) -> bool {
false
}
}
impl AttributeCast for Caster {
fn get(&self, value: &Value) -> Result<Value, CastError> {
Self::get(self, value)
}
fn set(&self, value: &Value) -> Result<Value, CastError> {
Self::set(self, value)
}
fn set_async<'a>(&'a self, value: &'a Value) -> BoxFuture<'a, Result<Value, CastError>> {
Box::pin(Self::set_async(self, value))
}
fn tidy(&self, value: Value) -> Value {
Self::tidy(self, value)
}
fn skips_empty(&self) -> bool {
Self::skips_empty(self)
}
}
type Factory = Arc<dyn Fn(Option<&str>) -> Result<Arc<dyn AttributeCast>, CastError> + Send + Sync>;
#[derive(Clone, Default)]
pub struct Registry {
aliases: Aliases,
custom: BTreeMap<String, Factory>,
}
impl fmt::Debug for Registry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Registry")
.field("aliases", &self.aliases)
.field("custom", &self.custom.keys().collect::<Vec<_>>())
.finish()
}
}
impl Registry {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_aliases(mut self, aliases: Aliases) -> Self {
self.aliases = aliases;
self
}
#[must_use]
pub fn with(
mut self,
name: impl Into<String>,
factory: impl Fn(Option<&str>) -> Result<Box<dyn AttributeCast>, CastError>
+ Send
+ Sync
+ 'static,
) -> Self {
self.custom.insert(
name.into(),
Arc::new(move |arguments| factory(arguments).map(Arc::from)),
);
self
}
pub fn parse(&self, spec: &str) -> Result<Arc<dyn AttributeCast>, CastError> {
let (name, arguments) = split_arguments(spec);
if let Some(factory) = self.custom.get(name) {
return factory(arguments);
}
let resolved = self.aliases.resolve(spec)?;
let (name, arguments) = split_arguments(&resolved);
if let Some(factory) = self.custom.get(name) {
return factory(arguments);
}
Ok(Arc::new(Caster::parse_with(spec, &self.aliases)?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tidy {
Integer,
Float,
Boolean,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Inner {
Plain,
Integer,
Float,
Text,
Boolean,
Decimal(u8),
Json {
unicode: bool,
empty: Empty,
collection: bool,
},
Date(DateSpec),
Hashed,
Encrypted(Sealed),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sealed {
Text,
Json { empty: Empty, collection: bool },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Empty {
List,
Object,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct DateSpec {
kind: Kind,
parse_set: bool,
get: Option<Arc<Pattern>>,
set: Option<Arc<Pattern>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Caster {
spec: String,
inner: Inner,
tidy: Option<Tidy>,
}
impl Caster {
pub fn parse(spec: &str) -> Result<Self, CastError> {
Self::parse_with(spec, &Aliases::default())
}
pub fn parse_with(spec: &str, aliases: &Aliases) -> Result<Self, CastError> {
let tidy = match spec {
"integer" => Some(Tidy::Integer),
"float" | "double" => Some(Tidy::Float),
"boolean" => Some(Tidy::Boolean),
_ => None,
};
let resolved = aliases.resolve(spec)?;
let (name, arguments) = split_arguments(&resolved);
let inner = match name {
"" => Inner::Plain,
"integer" | "int" => Inner::Integer,
"float" | "double" | "real" => Inner::Float,
"string" => Inner::Text,
"boolean" | "bool" => Inner::Boolean,
"decimal" => Inner::Decimal(decimal_places(spec, arguments)?),
"json" if arguments == Some("unicode") => Inner::Json {
unicode: true,
empty: Empty::List,
collection: false,
},
"array" | "json" | "collection" => Inner::Json {
unicode: false,
empty: Empty::List,
collection: name == "collection",
},
"object" => Inner::Json {
unicode: false,
empty: Empty::Object,
collection: false,
},
"hashed" if arguments.is_none() => Inner::Hashed,
"encrypted" => Inner::Encrypted(match arguments {
None => Sealed::Text,
Some("array" | "json") => Sealed::Json {
empty: Empty::List,
collection: false,
},
Some("collection") => Sealed::Json {
empty: Empty::List,
collection: true,
},
Some("object") => Sealed::Json {
empty: Empty::Object,
collection: false,
},
Some(_) => return Err(CastError::Unsupported(spec.to_owned())),
}),
other => match class_kind(other) {
Some(kind) => Inner::Date(date_spec(spec, kind, arguments)?),
None => return Err(CastError::Unsupported(spec.to_owned())),
},
};
Ok(Self {
spec: spec.to_owned(),
inner,
tidy,
})
}
pub fn get(&self, value: &Value) -> Result<Value, CastError> {
if value.is_null() {
return Ok(Value::Null);
}
match &self.inner {
Inner::Plain => Ok(value.clone()),
Inner::Integer => to_integer(&self.spec, value),
Inner::Float => to_float(&self.spec, value),
Inner::Text => to_text(&self.spec, value),
Inner::Boolean => Ok(Value::Bool(to_bool(value))),
Inner::Decimal(places) => to_decimal(&self.spec, value, *places),
Inner::Json {
empty, collection, ..
} => from_json(&self.spec, value, *empty, *collection),
Inner::Date(date) => date.get(&self.spec, value),
Inner::Hashed => Ok(value.clone()),
Inner::Encrypted(sealed) => self.open(*sealed, value),
}
}
pub fn set(&self, value: &Value) -> Result<Value, CastError> {
match &self.inner {
Inner::Json { .. } if value.is_null() => Ok(Value::Null),
Inner::Json { unicode, .. } => Ok(Value::String(to_json(value, *unicode))),
Inner::Date(date) => date.set(&self.spec, value),
Inner::Hashed if value.is_null() => Ok(Value::Null),
Inner::Hashed => Err(CastError::NeedsAsync(self.spec.clone())),
Inner::Encrypted(sealed) => self.seal(*sealed, value),
_ => Ok(value.clone()),
}
}
pub async fn set_async(&self, value: &Value) -> Result<Value, CastError> {
if !matches!(self.inner, Inner::Hashed) || value.is_null() {
return self.set(value);
}
let text = match to_text(&self.spec, value)? {
Value::String(text) => text,
_ => return Err(invalid(&self.spec, "only text can be hashed")),
};
self.inside_the_application()?;
if is_bcrypt_hash(&text) {
return if fits_the_configuration(&text, laravel::config().hashing.rounds) {
Ok(Value::String(text))
} else {
Err(invalid(
&self.spec,
"the bcrypt hash does not match the configured algorithm and rounds",
))
};
}
let hash = laravel::hash::make(&text)
.await
.map_err(|error| failed(&self.spec, &error))?;
Ok(Value::String(hash.as_str().to_owned()))
}
fn open(&self, sealed: Sealed, value: &Value) -> Result<Value, CastError> {
let Value::String(payload) = value else {
return Err(invalid(&self.spec, "an encrypted value is text"));
};
self.inside_the_application()?;
let plain =
laravel::crypt::decrypt_string(payload).map_err(|error| failed(&self.spec, &error))?;
match sealed {
Sealed::Text => Ok(Value::String(plain)),
Sealed::Json { empty, collection } => {
from_json(&self.spec, &Value::String(plain), empty, collection)
}
}
}
fn seal(&self, sealed: Sealed, value: &Value) -> Result<Value, CastError> {
if value.is_null() {
return Ok(Value::Null);
}
let plain = match sealed {
Sealed::Text => match to_text(&self.spec, value)? {
Value::String(text) => text,
_ => return Err(invalid(&self.spec, "only text can be encrypted")),
},
Sealed::Json { .. } => to_json(value, false),
};
self.inside_the_application()?;
let payload =
laravel::crypt::encrypt_string(&plain).map_err(|error| failed(&self.spec, &error))?;
Ok(Value::String(payload))
}
fn inside_the_application(&self) -> Result<(), CastError> {
if laravel::context::Context::current().is_some() {
return Ok(());
}
Err(failed(
&self.spec,
&"it needs the application: a request, a command, `Application::scope` or `laravel::task::spawn`",
))
}
fn tidy(&self, value: Value) -> Value {
match (self.tidy, &value) {
(_, Value::Null) | (None, _) => value,
(Some(Tidy::Integer), _) => integer_value(&value).map_or(value, Value::Number),
(Some(Tidy::Float), _) => float_value(&value)
.and_then(Number::from_f64)
.map_or(value, Value::Number),
(Some(Tidy::Boolean), _) => Value::Bool(filter_bool(&value)),
}
}
fn skips_empty(&self) -> bool {
self.tidy.is_some()
}
}
pub trait IntoCast {
fn into_cast(self, registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError>;
}
impl IntoCast for &str {
fn into_cast(self, registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
registry.parse(self)
}
}
impl IntoCast for String {
fn into_cast(self, registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
registry.parse(&self)
}
}
impl IntoCast for &String {
fn into_cast(self, registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
registry.parse(self)
}
}
impl IntoCast for Arc<dyn AttributeCast> {
fn into_cast(self, _registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
Ok(self)
}
}
impl IntoCast for Box<dyn AttributeCast> {
fn into_cast(self, _registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
Ok(Arc::from(self))
}
}
impl<C: AttributeCast + 'static> IntoCast for C {
fn into_cast(self, _registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
Ok(Arc::new(self))
}
}
#[derive(Debug, Clone)]
pub enum Spec {
Text(String),
Cast(Arc<dyn AttributeCast>),
}
impl From<&str> for Spec {
fn from(text: &str) -> Self {
Self::Text(text.to_owned())
}
}
impl From<String> for Spec {
fn from(text: String) -> Self {
Self::Text(text)
}
}
impl<C: AttributeCast + 'static> From<C> for Spec {
fn from(cast: C) -> Self {
Self::Cast(Arc::new(cast))
}
}
impl IntoCast for Spec {
fn into_cast(self, registry: &Registry) -> Result<Arc<dyn AttributeCast>, CastError> {
match self {
Self::Text(text) => registry.parse(&text),
Self::Cast(cast) => Ok(cast),
}
}
}
#[macro_export]
macro_rules! casts {
($($field:expr => $cast:expr),* $(,)?) => {
[$(($field, $crate::dynamic::Spec::from($cast))),*]
};
}
#[derive(Debug, Clone, Default)]
pub struct CastSet(BTreeMap<String, Arc<dyn AttributeCast>>);
impl CastSet {
pub fn parse<K, V>(casts: impl IntoIterator<Item = (K, V)>) -> Result<Self, CastError>
where
K: Into<String>,
V: IntoCast,
{
Self::parse_in(casts, &Registry::default())
}
pub fn parse_with<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
aliases: &Aliases,
) -> Result<Self, CastError>
where
K: Into<String>,
V: IntoCast,
{
Self::parse_in(casts, &Registry::new().with_aliases(aliases.clone()))
}
pub fn parse_in<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
registry: &Registry,
) -> Result<Self, CastError>
where
K: Into<String>,
V: IntoCast,
{
casts
.into_iter()
.map(|(field, cast)| Ok((field.into(), cast.into_cast(registry)?)))
.collect::<Result<_, CastError>>()
.map(Self)
}
#[must_use]
pub fn with(mut self, field: impl Into<String>, cast: impl AttributeCast + 'static) -> Self {
self.0.insert(field.into(), Arc::new(cast));
self
}
#[must_use]
pub fn get(&self, field: &str) -> Option<&dyn AttributeCast> {
self.0.get(field).map(Arc::as_ref)
}
pub fn apply(
&self,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError> {
let mut data = data.clone();
for (field, value) in &mut data {
let Some(caster) = self.0.get(field) else {
continue;
};
if caster.skips_empty() && value.as_str() == Some("") {
continue;
}
let cast = match mode {
Mode::Get => caster.get(value)?,
Mode::Set => caster.set(value)?,
};
*value = caster.tidy(cast);
}
Ok(data)
}
pub async fn apply_async(
&self,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError> {
let mut data = data.clone();
for (field, value) in &mut data {
let Some(caster) = self.0.get(field) else {
continue;
};
if caster.skips_empty() && value.as_str() == Some("") {
continue;
}
let cast = match mode {
Mode::Get => caster.get(value)?,
Mode::Set => caster.set_async(value).await?,
};
*value = caster.tidy(cast);
}
Ok(data)
}
}
pub fn cast_array<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError>
where
K: Into<String>,
V: IntoCast,
{
CastSet::parse(casts)?.apply(data, mode)
}
pub async fn cast_array_async<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError>
where
K: Into<String>,
V: IntoCast,
{
CastSet::parse(casts)?.apply_async(data, mode).await
}
pub fn cast_array_in<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
registry: &Registry,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError>
where
K: Into<String>,
V: IntoCast,
{
CastSet::parse_in(casts, registry)?.apply(data, mode)
}
pub async fn cast_array_in_async<K, V>(
casts: impl IntoIterator<Item = (K, V)>,
registry: &Registry,
data: &Map<String, Value>,
mode: Mode,
) -> Result<Map<String, Value>, CastError>
where
K: Into<String>,
V: IntoCast,
{
CastSet::parse_in(casts, registry)?
.apply_async(data, mode)
.await
}
fn failed(spec: &str, error: &impl std::fmt::Display) -> CastError {
CastError::Failed {
cast: spec.to_owned(),
message: error.to_string(),
}
}
fn fits_the_configuration(hash: &str, rounds: u32) -> bool {
hash.starts_with("$2y$")
&& hash
.get(4..6)
.and_then(|cost| cost.parse::<u32>().ok())
.is_some_and(|cost| (4..=rounds).contains(&cost))
}
fn is_bcrypt_hash(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 60
&& bytes.starts_with(b"$2")
&& matches!(bytes[2], b'a' | b'b' | b'x' | b'y')
&& bytes[3] == b'$'
&& bytes[4..6].iter().all(u8::is_ascii_digit)
&& bytes[6] == b'$'
&& bytes[7..]
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'/'))
}
const MAX_DECIMAL_PLACES: u8 = 65;
const MAX_DECIMAL_DIGITS: usize = 1024;
const MAX_DECIMAL_EXPONENT: i32 = 1000;
fn decimal_places(spec: &str, arguments: Option<&str>) -> Result<u8, CastError> {
arguments.map_or(Ok(2), |places| {
places
.parse()
.ok()
.filter(|places| *places <= MAX_DECIMAL_PLACES)
.ok_or_else(|| {
invalid(
spec,
format!("the decimal places are a number from 0 to {MAX_DECIMAL_PLACES}"),
)
})
})
}
fn leading_number(text: &str) -> &str {
let text = text.trim_start();
let bytes = text.as_bytes();
let mut end = 0;
let digits = |from: usize| {
bytes[from..]
.iter()
.take_while(|byte| byte.is_ascii_digit())
.count()
};
if matches!(bytes.first(), Some(b'+' | b'-')) {
end += 1;
}
let whole = digits(end);
end += whole;
let mut fraction = 0;
if bytes.get(end) == Some(&b'.') {
fraction = digits(end + 1);
if whole > 0 || fraction > 0 {
end += 1 + fraction;
}
}
if whole == 0 && fraction == 0 {
return "";
}
if matches!(bytes.get(end), Some(b'e' | b'E')) {
let mut exponent = end + 1;
if matches!(bytes.get(exponent), Some(b'+' | b'-')) {
exponent += 1;
}
let power = digits(exponent);
if power > 0 {
end = exponent + power;
}
}
&text[..end]
}
fn leading_float(text: &str) -> f64 {
leading_number(text).parse().unwrap_or(0.0)
}
fn whole_number(text: &str) -> Option<Number> {
text.parse::<i64>()
.map(Number::from)
.or_else(|_| text.parse::<u64>().map(Number::from))
.ok()
}
fn truncated(float: f64) -> Option<Number> {
const BELOW: f64 = -9_223_372_036_854_777_856.0;
const ABOVE: f64 = 18_446_744_073_709_551_616.0;
if !(float > BELOW && float < ABOVE) {
return None;
}
Some(if float < 0.0 {
Number::from(float as i64)
} else {
Number::from(float as u64)
})
}
fn float_value(value: &Value) -> Option<f64> {
match value {
Value::Number(number) => number.as_f64(),
Value::String(text) => Some(leading_float(text)),
Value::Bool(flag) => Some(f64::from(u8::from(*flag))),
container => Some(f64::from(u8::from(is_filled(container)))),
}
}
fn is_filled(value: &Value) -> bool {
match value {
Value::Array(items) => !items.is_empty(),
Value::Object(fields) => !fields.is_empty(),
_ => false,
}
}
fn integer_value(value: &Value) -> Option<Number> {
match value {
Value::Number(number) if number.is_f64() => number.as_f64().and_then(truncated),
Value::Number(number) => number
.as_i64()
.map(Number::from)
.or_else(|| number.as_u64().map(Number::from)),
Value::String(text) => match leading_number(text) {
"" => Some(Number::from(0)),
number if number.contains(['.', 'e', 'E']) => number.parse().ok().and_then(truncated),
number => whole_number(number),
},
Value::Bool(flag) => Some(Number::from(u8::from(*flag))),
container => Some(Number::from(u8::from(is_filled(container)))),
}
}
fn to_integer(spec: &str, value: &Value) -> Result<Value, CastError> {
integer_value(value)
.map(Value::Number)
.ok_or_else(|| invalid(spec, "the number does not fit in an integer"))
}
fn to_float(spec: &str, value: &Value) -> Result<Value, CastError> {
if matches!(value, Value::Array(_) | Value::Object(_)) {
return Err(invalid(spec, "an array is not a number"));
}
let float = float_value(value).ok_or_else(|| invalid(spec, "not a number"))?;
Number::from_f64(float)
.map(Value::Number)
.ok_or_else(|| invalid(spec, "a JSON number cannot be infinite or NaN"))
}
fn to_text(spec: &str, value: &Value) -> Result<Value, CastError> {
match value {
Value::String(_) => Ok(value.clone()),
Value::Bool(true) => Ok(Value::String("1".into())),
Value::Bool(false) => Ok(Value::String(String::new())),
Value::Number(number) => Ok(Value::String(match number.as_f64() {
Some(float) if number.is_f64() && float.fract() == 0.0 && float.abs() < 1e15 => {
format!("{float:.0}")
}
_ => number.to_string(),
})),
_ => Err(invalid(spec, "an array is not text")),
}
}
fn to_bool(value: &Value) -> bool {
match value {
Value::Bool(flag) => *flag,
Value::String(text) => matches!(
text.trim().to_lowercase().as_str(),
"1" | "true" | "on" | "yes"
),
Value::Number(number) => number.as_f64().is_some_and(|float| float != 0.0),
Value::Array(items) => !items.is_empty(),
Value::Object(fields) => !fields.is_empty(),
Value::Null => false,
}
}
fn filter_bool(value: &Value) -> bool {
match value {
Value::Bool(flag) => *flag,
Value::String(text) => matches!(
text.trim().to_lowercase().as_str(),
"1" | "true" | "on" | "yes"
),
Value::Number(number) => number.as_f64() == Some(1.0),
_ => false,
}
}
fn to_decimal(spec: &str, value: &Value, places: u8) -> Result<Value, CastError> {
let text = match value {
Value::String(text) => text.clone(),
Value::Number(number) => number.to_string(),
Value::Bool(flag) => if *flag { "1" } else { "" }.to_owned(),
_ => return Err(invalid(spec, "only a number or numeric text is a decimal")),
};
let decimal =
bounded_decimal(&text).ok_or_else(|| invalid(spec, format!("`{text}` is not a number")))?;
Ok(Value::String(round_half_up(&decimal, places)))
}
fn bounded_decimal(text: &str) -> Option<BigDecimal> {
let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
let (mantissa, exponent) = match unsigned.split_once(['e', 'E']) {
Some((mantissa, exponent)) => (mantissa, Some(exponent)),
None => (unsigned, None),
};
let digits = |text: &str| text.bytes().all(|byte| byte.is_ascii_digit());
if let Some(exponent) = exponent {
let power = exponent.parse::<i32>().ok()?;
if !(-MAX_DECIMAL_EXPONENT..=MAX_DECIMAL_EXPONENT).contains(&power) {
return None;
}
}
let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let length = whole.len() + fraction.len();
if length == 0 || length > MAX_DECIMAL_DIGITS || !digits(whole) || !digits(fraction) {
return None;
}
text.parse().ok()
}
fn round_half_up(decimal: &BigDecimal, places: u8) -> String {
let (units, _) = decimal
.with_scale_round(i64::from(places), RoundingMode::HalfUp)
.as_bigint_and_exponent();
let units = units.to_string();
let (sign, magnitude) = units
.strip_prefix('-')
.map_or(("", units.as_str()), |magnitude| ("-", magnitude));
let places = usize::from(places);
if places == 0 {
return format!("{sign}{magnitude}");
}
let digits = format!("{magnitude:0>width$}", width = places + 1);
let (whole, fraction) = digits.split_at(digits.len() - places);
format!("{sign}{whole}.{fraction}")
}
const MAX_JSON_DEPTH: usize = 127;
fn nests_deeper_than(text: &str, limit: usize) -> bool {
let (mut depth, mut in_string, mut escaped) = (0_usize, false, false);
text.bytes().any(|byte| {
match byte {
_ if escaped => escaped = false,
b'\\' if in_string => escaped = true,
b'"' => in_string = !in_string,
b'[' | b'{' if !in_string => depth += 1,
b']' | b'}' if !in_string => depth = depth.saturating_sub(1),
_ => {}
}
depth > limit
})
}
fn from_json(
spec: &str,
value: &Value,
empty: Empty,
collection: bool,
) -> Result<Value, CastError> {
let decoded = match value {
Value::Array(_) | Value::Object(_) if empty == Empty::Object => {
return Err(invalid(spec, "an array is not JSON text"));
}
Value::Array(_) | Value::Object(_) => return Ok(value.clone()),
Value::String(text) => match serde_json::from_str::<Value>(text) {
Ok(decoded) => decoded,
Err(_) if nests_deeper_than(text, MAX_JSON_DEPTH) => {
return Err(invalid(
spec,
format!("JSON nested deeper than {MAX_JSON_DEPTH} levels"),
));
}
Err(_) => Value::Null,
},
Value::Bool(false) => Value::Null,
scalar => match scalar {
Value::Bool(true) => Value::from(1),
other => other.clone(),
},
};
Ok(match (decoded, empty) {
(Value::Null, Empty::List) => Value::Array(Vec::new()),
(Value::Null, Empty::Object) => Value::Object(Map::new()),
(scalar @ (Value::Bool(_) | Value::Number(_) | Value::String(_)), _) if collection => {
Value::Array(vec![scalar])
}
(decoded, _) => decoded,
})
}
fn to_json(value: &Value, unicode: bool) -> String {
let text = serde_json::to_string(value).unwrap_or_else(|_| "null".into());
let mut out = String::with_capacity(text.len());
for character in text.chars() {
match character {
'/' => out.push_str("\\/"),
character if character.is_ascii() || unicode => out.push(character),
character => {
let mut units = [0u16; 2];
for unit in character.encode_utf16(&mut units) {
out.push_str(&format!("\\u{unit:04x}"));
}
}
}
}
out
}
fn class_kind(name: &str) -> Option<Kind> {
match name.rsplit(['\\', '/']).next()? {
"DateCast" => Some(Kind::Date),
"DateTimeCast" => Some(Kind::DateTime),
_ => None,
}
}
fn parse_flag(text: &str) -> bool {
matches!(
text.trim().to_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
}
fn pattern_argument(spec: &str, text: Option<&str>) -> Result<Option<Arc<Pattern>>, CastError> {
text.filter(|text| !matches!(*text, "" | "false"))
.map(|text| {
Pattern::compile(text)
.map(Arc::new)
.map_err(|error| invalid(spec, error.to_string()))
})
.transpose()
}
fn date_spec(spec: &str, kind: Kind, arguments: Option<&str>) -> Result<DateSpec, CastError> {
let mut parts = arguments.unwrap_or_default().split(',');
let parse_set = parts.next().is_some_and(parse_flag);
let get = pattern_argument(spec, parts.next())?;
let set = pattern_argument(spec, parts.next())?;
Ok(DateSpec {
kind,
parse_set,
get,
set,
})
}
impl DateSpec {
fn pattern(&self, own: Option<&Arc<Pattern>>) -> Arc<Pattern> {
own.map_or_else(|| config::pattern(self.kind), Arc::clone)
}
fn read(&self, value: &Value, origin: &Pattern) -> Option<DateTime> {
match value {
Value::Number(number) => number
.as_i64()
.or_else(|| number.as_f64().map(|float| float as i64))
.and_then(from_timestamp),
Value::String(text) if text.is_empty() => None,
Value::String(text) => {
if text.bytes().all(|byte| byte.is_ascii_digit()) {
match text.len() {
10 => return text.parse().ok().and_then(from_timestamp),
13 => {
return text
.parse::<i64>()
.ok()
.and_then(|ms| from_timestamp(ms / 1000));
}
_ => {}
}
}
origin
.parse(text)
.or_else(|| origin.parse_typed(text))
.or_else(|| free_text(text))
}
_ => None,
}
}
fn get(&self, spec: &str, value: &Value) -> Result<Value, CastError> {
refuse_containers(spec, value)?;
let Some(date) = self.read(value, config::storage(self.kind)) else {
return Ok(Value::Null);
};
Ok(Value::String(
self.pattern(self.get.as_ref()).format(&self.keep(date)),
))
}
fn set(&self, spec: &str, value: &Value) -> Result<Value, CastError> {
if matches!(value, Value::Null) || value.as_str() == Some("") {
return Ok(Value::Null);
}
refuse_containers(spec, value)?;
if !self.parse_set {
return Ok(value.clone());
}
Ok(match self.read(value, &self.pattern(self.set.as_ref())) {
Some(date) => Value::String(config::storage(self.kind).format(&self.keep(date))),
None => Value::Null,
})
}
fn keep(&self, date: DateTime) -> DateTime {
match self.kind {
Kind::Date => date.date().at(0, 0, 0, 0),
Kind::DateTime => date,
}
}
}
fn refuse_containers(spec: &str, value: &Value) -> Result<(), CastError> {
match value {
Value::Array(_) | Value::Object(_) => Err(invalid(spec, "an array is not a date")),
_ => Ok(()),
}
}
fn from_timestamp(seconds: i64) -> Option<DateTime> {
let moment = laravel::time::Timestamp::from_second(seconds).ok()?;
Some(moment.in_tz("UTC").ok()?.datetime())
}
fn free_text(text: &str) -> Option<DateTime> {
let text = text.trim().replace('/', "-");
let text = strip_zone(&text);
if let Ok(date_time) = text.parse::<DateTime>() {
return Some(date_time);
}
text.parse::<Date>().ok().map(|date| date.at(0, 0, 0, 0))
}
fn strip_zone(text: &str) -> &str {
if let Some(stripped) = text.strip_suffix(['Z', 'z']) {
return stripped;
}
let Some(time_at) = text.find(['T', ' ']) else {
return text;
};
match text[time_at..].rfind(['+', '-']) {
Some(sign) if is_offset(&text[time_at + sign + 1..]) => &text[..time_at + sign],
_ => text,
}
}
fn is_offset(text: &str) -> bool {
let (hours, minutes) = match text.len() {
2 => (Some(text), Some("00")),
4 => (text.get(..2), text.get(2..)),
5 if text.get(2..3) == Some(":") => (text.get(..2), text.get(3..)),
_ => return false,
};
let at_most = |part: Option<&str>, limit: u8| {
part.filter(|part| part.bytes().all(|byte| byte.is_ascii_digit()))
.and_then(|part| part.parse::<u8>().ok())
.is_some_and(|number| number <= limit)
};
at_most(hours, 23) && at_most(minutes, 59)
}