1#[cfg(feature = "format")]
6use crate::json::push_js_number;
7use crate::json::{Out, push_u64, u64_len};
8use crate::plural::{Whole, shortest_whole};
9use crate::text::{Key, MAX_NESTING, Text};
10use std::borrow::Cow;
11use std::fmt;
12use std::sync::Arc;
13
14#[derive(Debug, Clone)]
21#[non_exhaustive]
22pub enum Arg<'a> {
23 Str(&'a str),
25 String(Arc<str>),
27 Int(i64),
29 #[cfg(feature = "format")]
32 Float(f64),
33 Bool(bool),
35 Null,
37 Text(Box<Text>),
39 #[cfg(feature = "format")]
52 Number {
53 value: crate::Number,
55 format: Option<Cow<'a, str>>,
57 },
58 #[cfg(feature = "format")]
63 Date(crate::DateArg<'a>),
64}
65
66#[cfg(feature = "format")]
67impl<'a> Arg<'a> {
68 #[must_use]
78 pub fn date(at: impl Into<crate::Timestamp>) -> Self {
79 Arg::Date(crate::DateArg::date(at.into(), None))
80 }
81
82 #[must_use]
96 pub fn date_as(at: impl Into<crate::Timestamp>, name: impl Into<Cow<'a, str>>) -> Self {
97 Arg::Date(crate::DateArg::date(at.into(), Some(name.into())))
98 }
99
100 #[must_use]
111 pub fn relative(at: impl Into<crate::Timestamp>) -> Self {
112 Arg::Date(crate::DateArg::relative(at.into()))
113 }
114}
115
116impl PartialEq for Arg<'_> {
117 fn eq(&self, other: &Self) -> bool {
118 match (self, other) {
119 (a, b) if a.as_str().is_some() || b.as_str().is_some() => a.as_str() == b.as_str(),
120 (Arg::Int(a), Arg::Int(b)) => a == b,
121 #[cfg(feature = "format")]
122 (Arg::Float(a), Arg::Float(b)) => a == b,
123 (Arg::Bool(a), Arg::Bool(b)) => a == b,
124 (Arg::Null, Arg::Null) => true,
125 (Arg::Text(a), Arg::Text(b)) => a.same(b),
126 #[cfg(feature = "format")]
127 (
128 Arg::Number {
129 value: a,
130 format: fa,
131 },
132 Arg::Number {
133 value: b,
134 format: fb,
135 },
136 ) => a == b && fa == fb,
137 #[cfg(feature = "format")]
138 (Arg::Date(a), Arg::Date(b)) => a == b,
139 _ => false,
140 }
141 }
142}
143
144pub(crate) struct Small {
146 bytes: [u8; 32],
147 len: usize,
148}
149
150impl Small {
151 pub(crate) fn new() -> Self {
152 Small {
153 bytes: [0; 32],
154 len: 0,
155 }
156 }
157
158 pub(crate) fn as_str(&self) -> &str {
159 std::str::from_utf8(self.bytes.get(..self.len).unwrap_or(&[])).unwrap_or("")
160 }
161}
162
163impl Out for Small {
164 fn push_str(&mut self, s: &str) {
165 let end = self.len + s.len();
166 if let Some(slot) = self.bytes.get_mut(self.len..end) {
167 slot.copy_from_slice(s.as_bytes());
168 self.len = end;
169 }
170 }
171
172 fn push(&mut self, c: char) {
173 self.push_str(c.encode_utf8(&mut [0; 4]));
174 }
175}
176
177pub(crate) fn escape_html(out: &mut dyn fmt::Write, s: &str) -> fmt::Result {
179 let mut from = 0;
180 for (i, b) in s.bytes().enumerate() {
181 let entity = match b {
182 b'&' => "&",
183 b'<' => "<",
184 b'>' => ">",
185 b'"' => """,
186 b'\'' => "'",
187 _ => continue,
188 };
189 out.write_str(s.get(from..i).unwrap_or(""))?;
190 out.write_str(entity)?;
191 from = i + 1;
192 }
193 out.write_str(s.get(from..).unwrap_or(""))
194}
195
196pub(crate) struct Escape<'w>(pub(crate) &'w mut dyn fmt::Write);
198
199impl fmt::Write for Escape<'_> {
200 fn write_str(&mut self, s: &str) -> fmt::Result {
201 escape_html(self.0, s)
202 }
203}
204
205impl Arg<'_> {
206 fn as_str(&self) -> Option<&str> {
207 match self {
208 Arg::Str(s) => Some(s),
209 Arg::String(s) => Some(s),
210 _ => None,
211 }
212 }
213
214 pub(crate) fn write(&self, out: &mut String) {
215 match self {
216 Arg::Str(s) => out.push_str(s),
217 Arg::String(s) => out.push_str(s),
218 Arg::Text(t) => {
219 let _ = t.show(out);
221 }
222 #[cfg(feature = "format")]
223 Arg::Number { value, format } => {
224 let _ = crate::format::api::write_in(None, None, *value, format.as_deref(), out);
225 }
226 #[cfg(feature = "format")]
227 Arg::Date(d) => {
228 let _ = d.write_in(None, None, out);
229 }
230 other => other.scalar(out),
231 }
232 }
233
234 fn scalar<O: Out + ?Sized>(&self, out: &mut O) {
236 match *self {
237 Arg::Int(n) => {
238 if n < 0 {
239 out.push('-');
240 }
241 push_u64(out, n.unsigned_abs());
242 }
243 #[cfg(feature = "format")]
244 Arg::Float(v) => push_js_number(out, v),
245 Arg::Bool(b) => out.push_str(if b { "true" } else { "false" }),
246 Arg::Null => out.push_str("null"),
247 Arg::Str(_) | Arg::String(_) | Arg::Text(_) => {}
248 #[cfg(feature = "format")]
249 Arg::Number { .. } | Arg::Date(_) => {}
250 }
251 }
252
253 pub(crate) fn emit(&self, out: &mut dyn fmt::Write, html: bool) -> fmt::Result {
256 match self {
257 Arg::Str(s) if html => escape_html(out, s),
258 Arg::String(s) if html => escape_html(out, s),
259 Arg::Str(s) => out.write_str(s),
260 Arg::String(s) => out.write_str(s),
261 Arg::Text(t) if html && !t.is_html() => t.emit(&mut Escape(out)),
263 Arg::Text(t) => t.emit(out),
264 #[cfg(feature = "format")]
265 Arg::Number { value, format } => {
266 crate::format::api::write_in(None, None, *value, format.as_deref(), out)
267 }
268 #[cfg(feature = "format")]
269 Arg::Date(d) => d.write_in(None, None, out),
270 other => {
271 let mut b = Small::new();
272 other.scalar(&mut b);
273 out.write_str(b.as_str())
274 }
275 }
276 }
277
278 pub(crate) fn len(&self) -> usize {
281 match self {
282 Arg::Str(s) => s.len(),
283 Arg::String(s) => s.len(),
284 Arg::Int(n) => usize::from(*n < 0) + u64_len(n.unsigned_abs()),
285 #[cfg(feature = "format")]
286 Arg::Float(_) => MAX_SCALAR_LEN,
287 Arg::Bool(true) | Arg::Null => 4,
288 Arg::Bool(false) => 5,
289 Arg::Text(_) => MAX_SCALAR_LEN,
290 #[cfg(feature = "format")]
292 Arg::Number { .. } | Arg::Date(_) => 2 * MAX_SCALAR_LEN,
293 }
294 }
295}
296
297impl<'a> From<&'a str> for Arg<'a> {
298 fn from(s: &'a str) -> Self {
299 Arg::Str(s)
300 }
301}
302
303impl From<&String> for Arg<'_> {
305 fn from(s: &String) -> Self {
306 Arg::String(Arc::from(s.as_str()))
307 }
308}
309
310impl From<String> for Arg<'_> {
311 fn from(s: String) -> Self {
312 Arg::String(Arc::from(s))
313 }
314}
315
316impl From<Arc<str>> for Arg<'_> {
317 fn from(s: Arc<str>) -> Self {
318 Arg::String(s)
319 }
320}
321
322impl From<Box<str>> for Arg<'_> {
323 fn from(s: Box<str>) -> Self {
324 Arg::String(Arc::from(s))
325 }
326}
327
328impl<'a> From<Cow<'a, str>> for Arg<'a> {
329 fn from(s: Cow<'a, str>) -> Self {
330 match s {
331 Cow::Borrowed(s) => Arg::Str(s),
332 Cow::Owned(s) => Arg::from(s),
333 }
334 }
335}
336
337macro_rules! int_args {
338 ($($t:ty),*) => {$(
339 impl From<$t> for Arg<'_> {
340 fn from(n: $t) -> Self {
341 Arg::Int(i64::from(n))
342 }
343 }
344 )*};
345}
346int_args!(i8, i16, i32, i64, u8, u16, u32);
347
348impl From<u64> for Arg<'_> {
351 fn from(n: u64) -> Self {
352 if n <= SAFE {
353 Arg::Int(n as i64)
354 } else {
355 big(n as f64)
356 }
357 }
358}
359
360#[cfg(feature = "format")]
363impl From<u128> for Arg<'_> {
364 fn from(n: u128) -> Self {
365 match u64::try_from(n) {
366 Ok(n) => Arg::from(n),
367 Err(_) => Arg::Float(n as f64),
368 }
369 }
370}
371
372#[cfg(feature = "format")]
374impl From<i128> for Arg<'_> {
375 fn from(n: i128) -> Self {
376 if n.unsigned_abs() <= u128::from(SAFE) {
377 Arg::Int(n as i64)
378 } else {
379 Arg::Float(n as f64)
380 }
381 }
382}
383
384impl From<char> for Arg<'_> {
386 fn from(c: char) -> Self {
387 Arg::String(Arc::from(&*c.encode_utf8(&mut [0; 4])))
388 }
389}
390
391fn big(x: f64) -> Arg<'static> {
394 #[cfg(feature = "format")]
395 return Arg::Float(x);
396 #[cfg(not(feature = "format"))]
397 {
398 let mut s = String::new();
399 Count(CountRepr::Big(x)).write(&mut s);
400 Arg::String(Arc::from(s))
401 }
402}
403
404impl<'a> Arg<'a> {
405 #[must_use]
417 pub fn display(value: impl fmt::Display) -> Self {
418 Arg::String(Arc::from(value.to_string()))
419 }
420}
421
422impl From<usize> for Arg<'_> {
424 fn from(n: usize) -> Self {
425 Arg::Int(i64::try_from(n).unwrap_or(i64::MAX))
426 }
427}
428
429#[cfg(feature = "format")]
430impl From<f64> for Arg<'_> {
431 fn from(v: f64) -> Self {
432 Arg::Float(v)
433 }
434}
435
436#[cfg(feature = "format")]
437impl From<f32> for Arg<'_> {
438 fn from(v: f32) -> Self {
439 Arg::Float(f64::from(v))
440 }
441}
442
443impl From<bool> for Arg<'_> {
444 fn from(b: bool) -> Self {
445 Arg::Bool(b)
446 }
447}
448
449impl From<Text> for Arg<'_> {
450 fn from(t: Text) -> Self {
451 Arg::Text(Box::new(t))
452 }
453}
454
455impl From<Key> for Arg<'_> {
456 fn from(k: Key) -> Self {
457 Arg::Text(Box::new(k.args()))
458 }
459}
460
461pub(crate) const MAX_SCALAR_LEN: usize = 25;
465
466const SAFE: u64 = 1 << 53;
468
469#[derive(Debug, Clone, Copy, PartialEq)]
482pub struct Count(CountRepr);
483
484#[derive(Debug, Clone, Copy, PartialEq)]
485enum CountRepr {
486 Whole(u64),
488 Negative(i64),
490 Big(f64),
492 #[cfg(feature = "format")]
493 Float(f64),
494}
495
496impl Count {
497 pub(crate) fn whole(self) -> Option<Whole> {
499 match self.0 {
500 CountRepr::Whole(n) => Some(Whole::Int(n)),
501 CountRepr::Negative(_) => None,
502 CountRepr::Big(x) if x > 0.0 => Some(Whole::Big(x)),
503 CountRepr::Big(_) => None,
504 #[cfg(feature = "format")]
506 CountRepr::Float(x) if x >= 0.0 && x.fract() == 0.0 => {
507 if x <= SAFE as f64 {
509 Some(Whole::Int(x as u64))
510 } else {
511 Some(Whole::Big(x))
512 }
513 }
514 #[cfg(feature = "format")]
515 CountRepr::Float(_) => None,
516 }
517 }
518
519 pub(crate) fn as_f64(self) -> f64 {
521 match self.0 {
522 CountRepr::Whole(n) => n as f64,
523 CountRepr::Negative(n) => n as f64,
524 CountRepr::Big(x) => x,
525 #[cfg(feature = "format")]
526 CountRepr::Float(x) => x,
527 }
528 }
529
530 pub(crate) fn write<O: Out + ?Sized>(self, out: &mut O) {
532 match self.0 {
533 CountRepr::Whole(n) => push_u64(out, n),
534 CountRepr::Negative(n) => {
535 out.push('-');
536 push_u64(out, n.unsigned_abs());
537 }
538 CountRepr::Big(x) => {
539 if x < 0.0 {
540 out.push('-');
541 }
542 let (digits, zeros) = shortest_whole(x.abs()).unwrap_or((0, 0));
544 push_u64(out, digits);
545 out.push_zeros(zeros as usize);
546 }
547 #[cfg(feature = "format")]
548 CountRepr::Float(v) => push_js_number(out, v),
549 }
550 }
551
552 pub(crate) fn len(self) -> usize {
554 match self.0 {
555 CountRepr::Whole(n) => u64_len(n),
556 CountRepr::Negative(n) => 1 + u64_len(n.unsigned_abs()),
557 CountRepr::Big(_) => 21,
559 #[cfg(feature = "format")]
560 CountRepr::Float(_) => MAX_SCALAR_LEN,
561 }
562 }
563}
564
565impl From<i64> for Count {
566 fn from(n: i64) -> Self {
567 match u64::try_from(n) {
568 Ok(n) => Count::from(n),
569 Err(_) if n.unsigned_abs() <= SAFE => Count(CountRepr::Negative(n)),
570 Err(_) => Count(CountRepr::Big(n as f64)),
571 }
572 }
573}
574
575impl From<i32> for Count {
576 fn from(n: i32) -> Self {
577 Count::from(i64::from(n))
578 }
579}
580
581impl From<u64> for Count {
582 fn from(n: u64) -> Self {
583 Count(if n <= SAFE {
584 CountRepr::Whole(n)
585 } else {
586 CountRepr::Big(n as f64)
587 })
588 }
589}
590
591impl From<u32> for Count {
592 fn from(n: u32) -> Self {
593 Count(CountRepr::Whole(u64::from(n)))
594 }
595}
596
597impl From<usize> for Count {
598 fn from(n: usize) -> Self {
599 Count::from(n as u64)
600 }
601}
602
603#[cfg(feature = "format")]
604impl From<f64> for Count {
605 fn from(v: f64) -> Self {
606 Count(CountRepr::Float(v))
607 }
608}
609
610#[derive(Clone, Copy)]
614pub(crate) enum Hit<'x, 'a> {
615 Arg(&'x Arg<'a>),
616 Len(i64),
617}
618
619impl<'a> Hit<'_, 'a> {
620 #[inline]
622 pub(crate) fn with<R>(self, f: impl FnOnce(&Arg<'a>) -> R) -> R {
623 match self {
624 Hit::Arg(a) => f(a),
625 Hit::Len(n) => f(&Arg::Int(n)),
626 }
627 }
628}
629
630#[derive(Debug, Clone, PartialEq)]
631enum Name<'a> {
632 Named(&'a str),
633 Shared(Arc<str>),
635 Index(usize),
637}
638
639type Slot<'a> = (Name<'a>, Arg<'a>);
640
641const INLINE: usize = 4;
642
643const EMPTY: Slot<'static> = (Name::Index(0), Arg::Null);
644
645#[derive(Clone)]
661pub struct Args<'a> {
662 inline: [Slot<'a>; INLINE],
663 len: usize,
664 overflow: Vec<Slot<'a>>,
665 list_len: Option<usize>,
667 default: Option<&'a str>,
668}
669
670impl fmt::Debug for Args<'_> {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 let mut m = f.debug_map();
674 for (name, value) in self.slots() {
675 match name {
676 Name::Named(n) => m.entry(n, value),
677 Name::Shared(n) => m.entry(n, value),
678 Name::Index(i) => m.entry(i, value),
679 };
680 }
681 if let Some(d) = self.default {
682 m.entry(&"or", &d);
683 }
684 m.finish()
685 }
686}
687
688impl Default for Args<'_> {
689 fn default() -> Self {
690 Self::new()
691 }
692}
693
694impl<'a> Args<'a> {
695 #[must_use]
697 pub const fn new() -> Self {
698 Args {
699 inline: [EMPTY; INLINE],
700 len: 0,
701 overflow: Vec::new(),
702 list_len: None,
703 default: None,
704 }
705 }
706
707 #[must_use]
709 pub fn list<I>(items: I) -> Self
710 where
711 I: IntoIterator,
712 I::Item: Into<Arg<'a>>,
713 {
714 let mut args = Self::new();
715 args.extend_list(items.into_iter().map(Into::into));
716 args
717 }
718
719 pub(crate) fn extend_list(&mut self, items: impl Iterator<Item = Arg<'a>>) {
721 let mut n = self.list_len.unwrap_or(0);
722 for item in items {
723 if !matches!(&item, Arg::Text(t) if t.depth >= MAX_NESTING) {
725 self.push(Name::Index(n), item);
726 }
727 n += 1;
728 }
729 self.list_len = Some(n);
730 }
731
732 pub(crate) fn push_named(&mut self, name: Cow<'a, str>, value: Arg<'a>) {
733 let name = match name {
734 Cow::Borrowed(n) => Name::Named(n),
735 Cow::Owned(n) => Name::Shared(Arc::from(n)),
736 };
737 self.push(name, value);
738 }
739
740 pub(crate) fn same(&self, other: &Self) -> bool {
742 self.list_len == other.list_len && self.slots() == other.slots()
743 }
744
745 pub(crate) fn is_empty(&self) -> bool {
747 self.len == 0 && self.overflow.is_empty() && self.list_len.is_none()
748 }
749
750 fn push(&mut self, name: Name<'a>, value: Arg<'a>) {
751 if let Some(slot) = self.inline.get_mut(self.len) {
752 *slot = (name, value);
753 self.len += 1;
754 } else {
755 if self.overflow.is_empty() {
757 self.overflow.reserve(2 * INLINE);
758 self.overflow
759 .extend(self.inline.iter_mut().map(|s| std::mem::replace(s, EMPTY)));
760 }
761 self.overflow.push((name, value));
762 }
763 }
764
765 #[must_use]
767 pub fn arg(mut self, name: &'a str, value: impl Into<Arg<'a>>) -> Self {
768 self.push(Name::Named(name), value.into());
769 self
770 }
771
772 #[must_use]
774 pub fn str(self, name: &'a str, value: &'a str) -> Self {
775 self.arg(name, Arg::Str(value))
776 }
777
778 #[must_use]
780 pub fn int(self, name: &'a str, value: i64) -> Self {
781 self.arg(name, Arg::Int(value))
782 }
783
784 #[cfg(feature = "format")]
786 #[must_use]
787 pub fn float(self, name: &'a str, value: f64) -> Self {
788 self.arg(name, Arg::Float(value))
789 }
790
791 #[must_use]
793 pub fn bool(self, name: &'a str, value: bool) -> Self {
794 self.arg(name, Arg::Bool(value))
795 }
796
797 #[must_use]
799 pub fn null(self, name: &'a str) -> Self {
800 self.arg(name, Arg::Null)
801 }
802
803 #[must_use]
806 pub fn or(mut self, default: &'a str) -> Self {
807 self.default = Some(default);
808 self
809 }
810
811 pub(crate) fn default_text(&self) -> Option<&'a str> {
812 self.default.filter(|d| !d.is_empty())
813 }
814
815 pub(crate) fn default_raw(&self) -> Option<&'a str> {
817 self.default
818 }
819
820 fn slots(&self) -> &[Slot<'a>] {
823 if self.overflow.is_empty() {
824 self.inline.get(..self.len).unwrap_or(&[])
825 } else {
826 &self.overflow
827 }
828 }
829
830 #[inline]
833 pub(crate) fn find(&self, name: &str) -> Option<Hit<'_, 'a>> {
834 self.lookup(name, true)
835 }
836
837 #[inline]
840 pub(crate) fn spread(&self, name: &str) -> Option<Hit<'_, 'a>> {
841 self.lookup(name, false)
842 }
843
844 #[inline]
847 fn lookup(&self, name: &str, length: bool) -> Option<Hit<'_, 'a>> {
848 let index = self.list_len.and_then(|_| canonical_index(name));
850 for (slot, value) in self.slots().iter().rev() {
851 let hit = match slot {
852 Name::Named(n) => same_name(n, name),
853 Name::Shared(n) => same_name(n, name),
854 Name::Index(i) => index == Some(*i),
855 };
856 if hit {
857 return Some(Hit::Arg(value));
858 }
859 }
860 match self.list_len {
861 Some(n) if length && name == "length" => Some(Hit::Len(n as i64)),
862 _ => None,
863 }
864 }
865
866 pub(crate) fn max_value_len(&self) -> usize {
870 let list = if self.list_len.is_some() {
871 MAX_SCALAR_LEN
872 } else {
873 0
874 };
875 self.slots()
876 .iter()
877 .map(|(_, v)| match v {
878 Arg::Str(s) => s.len(),
879 Arg::String(s) => s.len(),
880 _ => MAX_SCALAR_LEN,
881 })
882 .fold(list, usize::max)
883 }
884}
885
886#[inline(always)]
889fn same_name(n: &str, name: &str) -> bool {
890 n.len() == name.len() && n.bytes().zip(name.bytes()).all(|(a, b)| a == b)
891}
892
893fn canonical_index(name: &str) -> Option<usize> {
895 let b = name.as_bytes();
896 if b.is_empty() || (b.len() > 1 && b[0] == b'0') || !b.iter().all(u8::is_ascii_digit) {
897 return None;
898 }
899 name.parse().ok()
900}