#[cfg(feature = "format")]
use crate::json::push_js_number;
use crate::json::{Out, push_u64, u64_len};
use crate::plural::{Whole, shortest_whole};
use crate::text::{Key, MAX_NESTING, Text};
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Arg<'a> {
Str(&'a str),
String(Arc<str>),
Int(i64),
#[cfg(feature = "format")]
Float(f64),
Bool(bool),
Null,
Text(Box<Text>),
#[cfg(feature = "format")]
Number {
value: crate::Number,
format: Option<Cow<'a, str>>,
},
#[cfg(feature = "format")]
Date(crate::DateArg<'a>),
}
#[cfg(feature = "format")]
impl<'a> Arg<'a> {
#[must_use]
pub fn date(at: impl Into<crate::Timestamp>) -> Self {
Arg::Date(crate::DateArg::date(at.into(), None))
}
#[must_use]
pub fn date_as(at: impl Into<crate::Timestamp>, name: impl Into<Cow<'a, str>>) -> Self {
Arg::Date(crate::DateArg::date(at.into(), Some(name.into())))
}
#[must_use]
pub fn relative(at: impl Into<crate::Timestamp>) -> Self {
Arg::Date(crate::DateArg::relative(at.into()))
}
}
impl PartialEq for Arg<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(a, b) if a.as_str().is_some() || b.as_str().is_some() => a.as_str() == b.as_str(),
(Arg::Int(a), Arg::Int(b)) => a == b,
#[cfg(feature = "format")]
(Arg::Float(a), Arg::Float(b)) => a == b,
(Arg::Bool(a), Arg::Bool(b)) => a == b,
(Arg::Null, Arg::Null) => true,
(Arg::Text(a), Arg::Text(b)) => a.same(b),
#[cfg(feature = "format")]
(
Arg::Number {
value: a,
format: fa,
},
Arg::Number {
value: b,
format: fb,
},
) => a == b && fa == fb,
#[cfg(feature = "format")]
(Arg::Date(a), Arg::Date(b)) => a == b,
_ => false,
}
}
}
pub(crate) struct Small {
bytes: [u8; 32],
len: usize,
}
impl Small {
pub(crate) fn new() -> Self {
Small {
bytes: [0; 32],
len: 0,
}
}
pub(crate) fn as_str(&self) -> &str {
std::str::from_utf8(self.bytes.get(..self.len).unwrap_or(&[])).unwrap_or("")
}
}
impl Out for Small {
fn push_str(&mut self, s: &str) {
let end = self.len + s.len();
if let Some(slot) = self.bytes.get_mut(self.len..end) {
slot.copy_from_slice(s.as_bytes());
self.len = end;
}
}
fn push(&mut self, c: char) {
self.push_str(c.encode_utf8(&mut [0; 4]));
}
}
pub(crate) fn escape_html(out: &mut dyn fmt::Write, s: &str) -> fmt::Result {
let mut from = 0;
for (i, b) in s.bytes().enumerate() {
let entity = match b {
b'&' => "&",
b'<' => "<",
b'>' => ">",
b'"' => """,
b'\'' => "'",
_ => continue,
};
out.write_str(s.get(from..i).unwrap_or(""))?;
out.write_str(entity)?;
from = i + 1;
}
out.write_str(s.get(from..).unwrap_or(""))
}
pub(crate) struct Escape<'w>(pub(crate) &'w mut dyn fmt::Write);
impl fmt::Write for Escape<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
escape_html(self.0, s)
}
}
impl Arg<'_> {
fn as_str(&self) -> Option<&str> {
match self {
Arg::Str(s) => Some(s),
Arg::String(s) => Some(s),
_ => None,
}
}
pub(crate) fn write(&self, out: &mut String) {
match self {
Arg::Str(s) => out.push_str(s),
Arg::String(s) => out.push_str(s),
Arg::Text(t) => {
let _ = t.show(out);
}
#[cfg(feature = "format")]
Arg::Number { value, format } => {
let _ = crate::format::api::write_in(None, None, *value, format.as_deref(), out);
}
#[cfg(feature = "format")]
Arg::Date(d) => {
let _ = d.write_in(None, None, out);
}
other => other.scalar(out),
}
}
fn scalar<O: Out + ?Sized>(&self, out: &mut O) {
match *self {
Arg::Int(n) => {
if n < 0 {
out.push('-');
}
push_u64(out, n.unsigned_abs());
}
#[cfg(feature = "format")]
Arg::Float(v) => push_js_number(out, v),
Arg::Bool(b) => out.push_str(if b { "true" } else { "false" }),
Arg::Null => out.push_str("null"),
Arg::Str(_) | Arg::String(_) | Arg::Text(_) => {}
#[cfg(feature = "format")]
Arg::Number { .. } | Arg::Date(_) => {}
}
}
pub(crate) fn emit(&self, out: &mut dyn fmt::Write, html: bool) -> fmt::Result {
match self {
Arg::Str(s) if html => escape_html(out, s),
Arg::String(s) if html => escape_html(out, s),
Arg::Str(s) => out.write_str(s),
Arg::String(s) => out.write_str(s),
Arg::Text(t) if html && !t.is_html() => t.emit(&mut Escape(out)),
Arg::Text(t) => t.emit(out),
#[cfg(feature = "format")]
Arg::Number { value, format } => {
crate::format::api::write_in(None, None, *value, format.as_deref(), out)
}
#[cfg(feature = "format")]
Arg::Date(d) => d.write_in(None, None, out),
other => {
let mut b = Small::new();
other.scalar(&mut b);
out.write_str(b.as_str())
}
}
}
pub(crate) fn len(&self) -> usize {
match self {
Arg::Str(s) => s.len(),
Arg::String(s) => s.len(),
Arg::Int(n) => usize::from(*n < 0) + u64_len(n.unsigned_abs()),
#[cfg(feature = "format")]
Arg::Float(_) => MAX_SCALAR_LEN,
Arg::Bool(true) | Arg::Null => 4,
Arg::Bool(false) => 5,
Arg::Text(_) => MAX_SCALAR_LEN,
#[cfg(feature = "format")]
Arg::Number { .. } | Arg::Date(_) => 2 * MAX_SCALAR_LEN,
}
}
}
impl<'a> From<&'a str> for Arg<'a> {
fn from(s: &'a str) -> Self {
Arg::Str(s)
}
}
impl From<&String> for Arg<'_> {
fn from(s: &String) -> Self {
Arg::String(Arc::from(s.as_str()))
}
}
impl From<String> for Arg<'_> {
fn from(s: String) -> Self {
Arg::String(Arc::from(s))
}
}
impl From<Arc<str>> for Arg<'_> {
fn from(s: Arc<str>) -> Self {
Arg::String(s)
}
}
impl From<Box<str>> for Arg<'_> {
fn from(s: Box<str>) -> Self {
Arg::String(Arc::from(s))
}
}
impl<'a> From<Cow<'a, str>> for Arg<'a> {
fn from(s: Cow<'a, str>) -> Self {
match s {
Cow::Borrowed(s) => Arg::Str(s),
Cow::Owned(s) => Arg::from(s),
}
}
}
macro_rules! int_args {
($($t:ty),*) => {$(
impl From<$t> for Arg<'_> {
fn from(n: $t) -> Self {
Arg::Int(i64::from(n))
}
}
)*};
}
int_args!(i8, i16, i32, i64, u8, u16, u32);
impl From<u64> for Arg<'_> {
fn from(n: u64) -> Self {
if n <= SAFE {
Arg::Int(n as i64)
} else {
big(n as f64)
}
}
}
#[cfg(feature = "format")]
impl From<u128> for Arg<'_> {
fn from(n: u128) -> Self {
match u64::try_from(n) {
Ok(n) => Arg::from(n),
Err(_) => Arg::Float(n as f64),
}
}
}
#[cfg(feature = "format")]
impl From<i128> for Arg<'_> {
fn from(n: i128) -> Self {
if n.unsigned_abs() <= u128::from(SAFE) {
Arg::Int(n as i64)
} else {
Arg::Float(n as f64)
}
}
}
impl From<char> for Arg<'_> {
fn from(c: char) -> Self {
Arg::String(Arc::from(&*c.encode_utf8(&mut [0; 4])))
}
}
fn big(x: f64) -> Arg<'static> {
#[cfg(feature = "format")]
return Arg::Float(x);
#[cfg(not(feature = "format"))]
{
let mut s = String::new();
Count(CountRepr::Big(x)).write(&mut s);
Arg::String(Arc::from(s))
}
}
impl<'a> Arg<'a> {
#[must_use]
pub fn display(value: impl fmt::Display) -> Self {
Arg::String(Arc::from(value.to_string()))
}
}
impl From<usize> for Arg<'_> {
fn from(n: usize) -> Self {
Arg::Int(i64::try_from(n).unwrap_or(i64::MAX))
}
}
#[cfg(feature = "format")]
impl From<f64> for Arg<'_> {
fn from(v: f64) -> Self {
Arg::Float(v)
}
}
#[cfg(feature = "format")]
impl From<f32> for Arg<'_> {
fn from(v: f32) -> Self {
Arg::Float(f64::from(v))
}
}
impl From<bool> for Arg<'_> {
fn from(b: bool) -> Self {
Arg::Bool(b)
}
}
impl From<Text> for Arg<'_> {
fn from(t: Text) -> Self {
Arg::Text(Box::new(t))
}
}
impl From<Key> for Arg<'_> {
fn from(k: Key) -> Self {
Arg::Text(Box::new(k.args()))
}
}
pub(crate) const MAX_SCALAR_LEN: usize = 25;
const SAFE: u64 = 1 << 53;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Count(CountRepr);
#[derive(Debug, Clone, Copy, PartialEq)]
enum CountRepr {
Whole(u64),
Negative(i64),
Big(f64),
#[cfg(feature = "format")]
Float(f64),
}
impl Count {
pub(crate) fn whole(self) -> Option<Whole> {
match self.0 {
CountRepr::Whole(n) => Some(Whole::Int(n)),
CountRepr::Negative(_) => None,
CountRepr::Big(x) if x > 0.0 => Some(Whole::Big(x)),
CountRepr::Big(_) => None,
#[cfg(feature = "format")]
CountRepr::Float(x) if x >= 0.0 && x.fract() == 0.0 => {
if x <= SAFE as f64 {
Some(Whole::Int(x as u64))
} else {
Some(Whole::Big(x))
}
}
#[cfg(feature = "format")]
CountRepr::Float(_) => None,
}
}
pub(crate) fn as_f64(self) -> f64 {
match self.0 {
CountRepr::Whole(n) => n as f64,
CountRepr::Negative(n) => n as f64,
CountRepr::Big(x) => x,
#[cfg(feature = "format")]
CountRepr::Float(x) => x,
}
}
pub(crate) fn write<O: Out + ?Sized>(self, out: &mut O) {
match self.0 {
CountRepr::Whole(n) => push_u64(out, n),
CountRepr::Negative(n) => {
out.push('-');
push_u64(out, n.unsigned_abs());
}
CountRepr::Big(x) => {
if x < 0.0 {
out.push('-');
}
let (digits, zeros) = shortest_whole(x.abs()).unwrap_or((0, 0));
push_u64(out, digits);
out.push_zeros(zeros as usize);
}
#[cfg(feature = "format")]
CountRepr::Float(v) => push_js_number(out, v),
}
}
pub(crate) fn len(self) -> usize {
match self.0 {
CountRepr::Whole(n) => u64_len(n),
CountRepr::Negative(n) => 1 + u64_len(n.unsigned_abs()),
CountRepr::Big(_) => 21,
#[cfg(feature = "format")]
CountRepr::Float(_) => MAX_SCALAR_LEN,
}
}
}
impl From<i64> for Count {
fn from(n: i64) -> Self {
match u64::try_from(n) {
Ok(n) => Count::from(n),
Err(_) if n.unsigned_abs() <= SAFE => Count(CountRepr::Negative(n)),
Err(_) => Count(CountRepr::Big(n as f64)),
}
}
}
impl From<i32> for Count {
fn from(n: i32) -> Self {
Count::from(i64::from(n))
}
}
impl From<u64> for Count {
fn from(n: u64) -> Self {
Count(if n <= SAFE {
CountRepr::Whole(n)
} else {
CountRepr::Big(n as f64)
})
}
}
impl From<u32> for Count {
fn from(n: u32) -> Self {
Count(CountRepr::Whole(u64::from(n)))
}
}
impl From<usize> for Count {
fn from(n: usize) -> Self {
Count::from(n as u64)
}
}
#[cfg(feature = "format")]
impl From<f64> for Count {
fn from(v: f64) -> Self {
Count(CountRepr::Float(v))
}
}
#[derive(Clone, Copy)]
pub(crate) enum Hit<'x, 'a> {
Arg(&'x Arg<'a>),
Len(i64),
}
impl<'a> Hit<'_, 'a> {
#[inline]
pub(crate) fn with<R>(self, f: impl FnOnce(&Arg<'a>) -> R) -> R {
match self {
Hit::Arg(a) => f(a),
Hit::Len(n) => f(&Arg::Int(n)),
}
}
}
#[derive(Debug, Clone, PartialEq)]
enum Name<'a> {
Named(&'a str),
Shared(Arc<str>),
Index(usize),
}
type Slot<'a> = (Name<'a>, Arg<'a>);
const INLINE: usize = 4;
const EMPTY: Slot<'static> = (Name::Index(0), Arg::Null);
#[derive(Clone)]
pub struct Args<'a> {
inline: [Slot<'a>; INLINE],
len: usize,
overflow: Vec<Slot<'a>>,
list_len: Option<usize>,
default: Option<&'a str>,
}
impl fmt::Debug for Args<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut m = f.debug_map();
for (name, value) in self.slots() {
match name {
Name::Named(n) => m.entry(n, value),
Name::Shared(n) => m.entry(n, value),
Name::Index(i) => m.entry(i, value),
};
}
if let Some(d) = self.default {
m.entry(&"or", &d);
}
m.finish()
}
}
impl Default for Args<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> Args<'a> {
#[must_use]
pub const fn new() -> Self {
Args {
inline: [EMPTY; INLINE],
len: 0,
overflow: Vec::new(),
list_len: None,
default: None,
}
}
#[must_use]
pub fn list<I>(items: I) -> Self
where
I: IntoIterator,
I::Item: Into<Arg<'a>>,
{
let mut args = Self::new();
args.extend_list(items.into_iter().map(Into::into));
args
}
pub(crate) fn extend_list(&mut self, items: impl Iterator<Item = Arg<'a>>) {
let mut n = self.list_len.unwrap_or(0);
for item in items {
if !matches!(&item, Arg::Text(t) if t.depth >= MAX_NESTING) {
self.push(Name::Index(n), item);
}
n += 1;
}
self.list_len = Some(n);
}
pub(crate) fn push_named(&mut self, name: Cow<'a, str>, value: Arg<'a>) {
let name = match name {
Cow::Borrowed(n) => Name::Named(n),
Cow::Owned(n) => Name::Shared(Arc::from(n)),
};
self.push(name, value);
}
pub(crate) fn same(&self, other: &Self) -> bool {
self.list_len == other.list_len && self.slots() == other.slots()
}
pub(crate) fn is_empty(&self) -> bool {
self.len == 0 && self.overflow.is_empty() && self.list_len.is_none()
}
fn push(&mut self, name: Name<'a>, value: Arg<'a>) {
if let Some(slot) = self.inline.get_mut(self.len) {
*slot = (name, value);
self.len += 1;
} else {
if self.overflow.is_empty() {
self.overflow.reserve(2 * INLINE);
self.overflow
.extend(self.inline.iter_mut().map(|s| std::mem::replace(s, EMPTY)));
}
self.overflow.push((name, value));
}
}
#[must_use]
pub fn arg(mut self, name: &'a str, value: impl Into<Arg<'a>>) -> Self {
self.push(Name::Named(name), value.into());
self
}
#[must_use]
pub fn str(self, name: &'a str, value: &'a str) -> Self {
self.arg(name, Arg::Str(value))
}
#[must_use]
pub fn int(self, name: &'a str, value: i64) -> Self {
self.arg(name, Arg::Int(value))
}
#[cfg(feature = "format")]
#[must_use]
pub fn float(self, name: &'a str, value: f64) -> Self {
self.arg(name, Arg::Float(value))
}
#[must_use]
pub fn bool(self, name: &'a str, value: bool) -> Self {
self.arg(name, Arg::Bool(value))
}
#[must_use]
pub fn null(self, name: &'a str) -> Self {
self.arg(name, Arg::Null)
}
#[must_use]
pub fn or(mut self, default: &'a str) -> Self {
self.default = Some(default);
self
}
pub(crate) fn default_text(&self) -> Option<&'a str> {
self.default.filter(|d| !d.is_empty())
}
pub(crate) fn default_raw(&self) -> Option<&'a str> {
self.default
}
fn slots(&self) -> &[Slot<'a>] {
if self.overflow.is_empty() {
self.inline.get(..self.len).unwrap_or(&[])
} else {
&self.overflow
}
}
#[inline]
pub(crate) fn find(&self, name: &str) -> Option<Hit<'_, 'a>> {
self.lookup(name, true)
}
#[inline]
pub(crate) fn spread(&self, name: &str) -> Option<Hit<'_, 'a>> {
self.lookup(name, false)
}
#[inline]
fn lookup(&self, name: &str, length: bool) -> Option<Hit<'_, 'a>> {
let index = self.list_len.and_then(|_| canonical_index(name));
for (slot, value) in self.slots().iter().rev() {
let hit = match slot {
Name::Named(n) => same_name(n, name),
Name::Shared(n) => same_name(n, name),
Name::Index(i) => index == Some(*i),
};
if hit {
return Some(Hit::Arg(value));
}
}
match self.list_len {
Some(n) if length && name == "length" => Some(Hit::Len(n as i64)),
_ => None,
}
}
pub(crate) fn max_value_len(&self) -> usize {
let list = if self.list_len.is_some() {
MAX_SCALAR_LEN
} else {
0
};
self.slots()
.iter()
.map(|(_, v)| match v {
Arg::Str(s) => s.len(),
Arg::String(s) => s.len(),
_ => MAX_SCALAR_LEN,
})
.fold(list, usize::max)
}
}
#[inline(always)]
fn same_name(n: &str, name: &str) -> bool {
n.len() == name.len() && n.bytes().zip(name.bytes()).all(|(a, b)| a == b)
}
fn canonical_index(name: &str) -> Option<usize> {
let b = name.as_bytes();
if b.is_empty() || (b.len() > 1 && b[0] == b'0') || !b.iter().all(u8::is_ascii_digit) {
return None;
}
name.parse().ok()
}