use std::fmt;
use std::sync::Arc;
use indexmap::IndexMap;
use laravel::str::Str;
use crate::support::{is_numeric, ucfirst};
#[derive(Clone)]
pub enum ReplaceValue {
Text(String),
Int(i64),
Float(f64),
Bool(bool),
Null,
Callback(Arc<dyn Fn(&str) -> String + Send + Sync>),
}
impl ReplaceValue {
pub fn callback(callback: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
Self::Callback(Arc::new(callback))
}
pub fn to_text(&self) -> String {
match self {
Self::Text(text) => text.clone(),
Self::Int(number) => number.to_string(),
Self::Float(number) => number.to_string(),
Self::Bool(true) => "1".to_owned(),
Self::Bool(false) | Self::Null | Self::Callback(_) => String::new(),
}
}
pub fn is_numeric(&self) -> bool {
match self {
Self::Int(_) => true,
Self::Float(number) => number.is_finite(),
Self::Text(text) => is_numeric(text),
_ => false,
}
}
pub fn as_number(&self) -> Option<f64> {
match self {
Self::Int(number) => Some(*number as f64),
Self::Float(number) if number.is_finite() => Some(*number),
Self::Text(text) if is_numeric(text) => text.trim().parse().ok(),
_ => None,
}
}
}
impl fmt::Debug for ReplaceValue {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Text(text) => formatter.debug_tuple("Text").field(text).finish(),
Self::Int(number) => formatter.debug_tuple("Int").field(number).finish(),
Self::Float(number) => formatter.debug_tuple("Float").field(number).finish(),
Self::Bool(value) => formatter.debug_tuple("Bool").field(value).finish(),
Self::Null => formatter.write_str("Null"),
Self::Callback(_) => formatter.write_str("Callback"),
}
}
}
macro_rules! from_integer {
($($type:ty),*) => {
$(impl From<$type> for ReplaceValue {
fn from(value: $type) -> Self {
Self::Int(value as i64)
}
})*
};
}
from_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
impl From<f32> for ReplaceValue {
fn from(value: f32) -> Self {
Self::Float(f64::from(value))
}
}
impl From<f64> for ReplaceValue {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<bool> for ReplaceValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<&str> for ReplaceValue {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for ReplaceValue {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<&String> for ReplaceValue {
fn from(value: &String) -> Self {
Self::Text(value.clone())
}
}
impl<T: Into<ReplaceValue>> From<Option<T>> for ReplaceValue {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}
#[derive(Debug, Clone, Default)]
pub struct Replace(IndexMap<String, ReplaceValue>);
impl Replace {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, name: impl Into<String>, value: impl Into<ReplaceValue>) -> Self {
self.insert(name, value);
self
}
pub fn insert(&mut self, name: impl Into<String>, value: impl Into<ReplaceValue>) -> &mut Self {
self.0.insert(name.into(), value.into());
self
}
pub fn get(&self, name: &str) -> Option<&ReplaceValue> {
self.0.get(name)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &ReplaceValue)> {
self.0.iter()
}
pub fn count(&self) -> Option<f64> {
self.get("count").and_then(ReplaceValue::as_number)
}
}
impl<K: Into<String>, V: Into<ReplaceValue>> FromIterator<(K, V)> for Replace {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut replace = Self::new();
for (name, value) in iter {
replace.insert(name, value);
}
replace
}
}
#[macro_export]
macro_rules! replace {
() => {
$crate::Replace::new()
};
($($name:tt => $value:expr),+ $(,)?) => {{
let mut replace = $crate::Replace::new();
$(replace.insert($crate::replace::name(stringify!($name)), $value);)+
replace
}};
}
#[doc(hidden)]
pub fn name(written: &str) -> &str {
written
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(written)
}
pub fn make_replacements(line: &str, replace: &Replace) -> String {
if replace.is_empty() {
return line.to_owned();
}
let mut line = line.to_owned();
let mut pairs: IndexMap<String, String> = IndexMap::new();
for (name, value) in replace.iter() {
if let ReplaceValue::Callback(callback) = value {
line = wrap(&line, name, callback.as_ref());
continue;
}
let value = value.to_text();
pairs.insert(format!(":{}", ucfirst(name)), ucfirst(&value));
pairs.insert(format!(":{}", name.to_uppercase()), value.to_uppercase());
pairs.insert(format!(":{name}"), value);
}
if pairs.is_empty() {
return line;
}
let pairs: Vec<(&str, &str)> = pairs.iter().map(|(from, to)| (from.as_str(), to.as_str())).collect();
line.swap(&pairs)
}
fn wrap(line: &str, name: &str, callback: &(dyn Fn(&str) -> String + Send + Sync)) -> String {
let open = format!("<{name}>");
let close = format!("</{name}>");
let mut result = String::with_capacity(line.len());
let mut rest = line;
while let Some(start) = rest.find(&open) {
let inner_start = start + open.len();
let after = &rest[inner_start..];
let closed = after.find(&close).filter(|end| !after[..*end].contains('\n'));
match closed {
Some(end) => {
result.push_str(&rest[..start]);
result.push_str(&callback(&after[..end]));
rest = &after[end + close.len()..];
}
None => {
let step = start + rest[start..].chars().next().map_or(1, char::len_utf8);
result.push_str(&rest[..step]);
rest = &rest[step..];
}
}
}
result.push_str(rest);
result
}