docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Value filters.
//!
//! A filter transforms the value of a placeholder before it is inserted:
//!
//! ```text
//! {{name | upper}}
//! {{nickname | default: "friend"}}
//! {{items | len}}
//! ```
//!
//! A filter receives the current value and its optional argument, and returns
//! the value for the next filter in the chain. The built in filters are
//! installed in [`FilterRegistry::default`], and a caller can add or replace one
//! with [`TemplateOptions::filter`](crate::TemplateOptions::filter).
//!
//! The built in filters are:
//!
//! - Text: `upper`, `lower`, `trim`, `default`, `len`, `join`
//! - Numbers: `round`, `fixed`, `thousands`, `percent`
//! - Dates, when the `dates` feature is on (it is on by default): `date`,
//!   `timezone`

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use serde_json::Value;

#[cfg(feature = "dates")]
use jiff::{Timestamp, ZonedDateTime, civil, fmt::strtime, tz::TimeZone};

/// A filter function.
///
/// The first argument is the current value, the second is the filter argument
/// written after a colon in the template, such as `"n/a"` in
/// `{{name | default: "n/a"}}`.
pub type FilterFn = dyn Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Send + Sync;

/// An error raised by a filter.
///
/// The message is shown as the reason in [`RenderError::FilterFailed`].
///
/// [`RenderError::FilterFailed`]: crate::RenderError::FilterFailed
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{message}")]
pub struct FilterError {
    message: String,
}

impl FilterError {
    /// Create a filter error with a human readable reason.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::FilterError;
    ///
    /// let error = FilterError::new("value is not a string");
    /// assert_eq!(error.to_string(), "value is not a string");
    /// ```
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

/// A named set of filters.
///
/// [`TemplateOptions::default`](crate::TemplateOptions::default) carries the
/// built in filters. Registering a filter with the same name replaces the built
/// in one for that set of options.
///
/// # Examples
///
/// ```
/// use docx_templating::{FilterError, FilterRegistry};
/// use serde_json::Value;
///
/// let mut registry = FilterRegistry::default();
/// registry.insert("shout", |value, _| {
///     let text = value
///         .as_str()
///         .ok_or_else(|| FilterError::new("value is not a string"))?;
///     Ok(Value::String(format!("{}!", text.to_uppercase())))
/// });
///
/// assert!(registry.contains("shout"));
/// assert!(registry.contains("upper"));
/// ```
#[derive(Clone)]
pub struct FilterRegistry {
    filters: HashMap<String, Arc<FilterFn>>,
}

impl FilterRegistry {
    /// Create a registry with the built in filters.
    ///
    /// The built in filters are the text filters `upper`, `lower`, `trim`,
    /// `default`, `len` and `join`, the number filters `round`, `fixed`,
    /// `thousands` and `percent`, and, when the `dates` feature is on, the
    /// date filters `date` and `timezone`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a filter, replacing any filter with the same name.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::FilterRegistry;
    /// use serde_json::Value;
    ///
    /// let mut registry = FilterRegistry::default();
    /// registry.insert("wrap", |value, argument| {
    ///     let open = argument.unwrap_or("[");
    ///     Ok(Value::String(format!("{open}{value}")))
    /// });
    /// ```
    pub fn insert<F>(&mut self, name: impl Into<String>, filter: F)
    where
        F: Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Send + Sync + 'static,
    {
        self.filters.insert(name.into(), Arc::new(filter));
    }

    /// Get a filter by name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&FilterFn> {
        self.filters.get(name).map(Arc::as_ref)
    }

    /// Whether a filter with this name is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.filters.contains_key(name)
    }

    /// Remove a filter and report whether it was present.
    pub fn remove(&mut self, name: &str) -> bool {
        self.filters.remove(name).is_some()
    }

    /// Number of registered filters.
    #[must_use]
    pub fn len(&self) -> usize {
        self.filters.len()
    }

    /// Whether no filter is registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.filters.is_empty()
    }
}

impl Default for FilterRegistry {
    fn default() -> Self {
        let mut filters = HashMap::new();
        filters.insert("upper".to_owned(), Arc::new(upper) as Arc<FilterFn>);
        filters.insert("lower".to_owned(), Arc::new(lower) as Arc<FilterFn>);
        filters.insert("trim".to_owned(), Arc::new(trim) as Arc<FilterFn>);
        filters.insert("default".to_owned(), Arc::new(default) as Arc<FilterFn>);
        filters.insert("len".to_owned(), Arc::new(len) as Arc<FilterFn>);
        filters.insert("join".to_owned(), Arc::new(join) as Arc<FilterFn>);
        filters.insert("round".to_owned(), Arc::new(round) as Arc<FilterFn>);
        filters.insert("fixed".to_owned(), Arc::new(fixed) as Arc<FilterFn>);
        filters.insert("thousands".to_owned(), Arc::new(thousands) as Arc<FilterFn>);
        filters.insert("percent".to_owned(), Arc::new(percent) as Arc<FilterFn>);
        #[cfg(feature = "dates")]
        {
            filters.insert("date".to_owned(), Arc::new(date) as Arc<FilterFn>);
            filters.insert("timezone".to_owned(), Arc::new(timezone) as Arc<FilterFn>);
        }
        Self { filters }
    }
}

impl fmt::Debug for FilterRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut names: Vec<&str> = self.filters.keys().map(String::as_str).collect();
        names.sort_unstable();
        f.debug_struct("FilterRegistry")
            .field("names", &names)
            .finish()
    }
}

/// Convert a scalar value to text for a filter that works on strings.
fn as_text(value: &Value) -> Result<String, FilterError> {
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::Number(number) => Ok(number.to_string()),
        Value::Bool(value) => Ok(value.to_string()),
        Value::Null => Err(FilterError::new("value is null")),
        Value::Array(_) => Err(FilterError::new("value is an array")),
        Value::Object(_) => Err(FilterError::new("value is an object")),
    }
}

fn upper(value: &Value, _argument: Option<&str>) -> Result<Value, FilterError> {
    Ok(Value::String(as_text(value)?.to_uppercase()))
}

fn lower(value: &Value, _argument: Option<&str>) -> Result<Value, FilterError> {
    Ok(Value::String(as_text(value)?.to_lowercase()))
}

fn trim(value: &Value, _argument: Option<&str>) -> Result<Value, FilterError> {
    Ok(Value::String(as_text(value)?.trim().to_owned()))
}

fn default(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let fallback = argument.ok_or_else(|| {
        FilterError::new("default needs a fallback value, for example | default: \"n/a\"")
    })?;
    if value.is_null() {
        Ok(Value::String(fallback.to_owned()))
    } else {
        Ok(value.clone())
    }
}

fn len(value: &Value, _argument: Option<&str>) -> Result<Value, FilterError> {
    let length = match value {
        Value::String(text) => text.chars().count(),
        Value::Array(items) => items.len(),
        Value::Object(map) => map.len(),
        Value::Null => 0,
        Value::Number(_) | Value::Bool(_) => {
            return Err(FilterError::new(
                "len needs a string, array or object, not a scalar",
            ));
        }
    };
    Ok(Value::from(length as u64))
}

fn join(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let separator = argument.unwrap_or(", ");
    let Value::Array(items) = value else {
        return Err(FilterError::new("join needs an array"));
    };

    let mut parts = Vec::with_capacity(items.len());
    for item in items {
        parts.push(as_text(item)?);
    }
    Ok(Value::String(parts.join(separator)))
}

/// The largest number of decimal places a number filter accepts.
const MAX_DECIMAL_PLACES: usize = 15;

/// Describe a value for an error message.
fn value_kind(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

/// Read a filter value as a finite number.
fn as_number(value: &Value, name: &str) -> Result<f64, FilterError> {
    let number = match value {
        Value::Number(number) => number.as_f64(),
        Value::String(text) => text.trim().parse::<f64>().ok(),
        Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => None,
    };

    match number {
        Some(number) if number.is_finite() => Ok(number),
        Some(_) => Err(FilterError::new(format!("{name} needs a finite number"))),
        None => Err(FilterError::new(format!(
            "{name} needs a number, found {}",
            match value {
                Value::String(text) => format!("'{text}'"),
                other => value_kind(other).to_owned(),
            }
        ))),
    }
}

/// Read the optional decimal place argument of a number filter.
fn decimal_places(
    argument: Option<&str>,
    name: &str,
    default: usize,
) -> Result<usize, FilterError> {
    let Some(raw) = argument else {
        return Ok(default);
    };

    let places = raw.trim().parse::<usize>().map_err(|_| {
        FilterError::new(format!(
            "{name} needs a whole number of decimal places, found '{raw}'"
        ))
    })?;

    if places > MAX_DECIMAL_PLACES {
        return Err(FilterError::new(format!(
            "{name} supports at most {MAX_DECIMAL_PLACES} decimal places"
        )));
    }
    Ok(places)
}

/// Turn formatted number text back into a JSON number.
fn number_from_text(text: &str) -> Result<Value, FilterError> {
    serde_json::from_str::<Value>(text)
        .map_err(|_| FilterError::new(format!("'{text}' is not a number")))
}

fn round(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let places = decimal_places(argument, "round", 0)?;
    let number = as_number(value, "round")?;
    let factor = 10f64.powi(places as i32);
    let rounded = (number * factor).round() / factor;
    number_from_text(&format!("{rounded:.places$}"))
}

fn fixed(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let Some(argument) = argument else {
        return Err(FilterError::new(
            "fixed needs a number of decimal places, for example | fixed: 2",
        ));
    };
    let places = decimal_places(Some(argument), "fixed", 0)?;
    let number = as_number(value, "fixed")?;
    Ok(Value::String(format!("{number:.places$}")))
}

fn thousands(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let separator = argument.unwrap_or(",");
    let text = match value {
        Value::Number(number) => number.to_string(),
        Value::String(text) => {
            let text = text.trim();
            as_number(value, "thousands")?;
            text.to_owned()
        }
        other => {
            return Err(FilterError::new(format!(
                "thousands needs a number, found {}",
                value_kind(other)
            )));
        }
    };
    Ok(Value::String(group_thousands(&text, separator)))
}

fn percent(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let places = decimal_places(argument, "percent", 0)?;
    let number = as_number(value, "percent")?;
    Ok(Value::String(format!("{:.places$}%", number * 100.0)))
}

/// Group the integer digits of a number in threes.
fn group_thousands(text: &str, separator: &str) -> String {
    let (mantissa, exponent) = match text.find(['e', 'E']) {
        Some(index) => (&text[..index], &text[index..]),
        None => (text, ""),
    };

    let (sign, mantissa) = match mantissa.strip_prefix('-') {
        Some(rest) => ("-", rest),
        None => ("", mantissa.strip_prefix('+').unwrap_or(mantissa)),
    };

    let (integer, fraction) = match mantissa.split_once('.') {
        Some((integer, fraction)) => (integer, Some(fraction)),
        None => (mantissa, None),
    };

    let mut grouped = String::with_capacity(text.len() + text.len() / 3);
    grouped.push_str(sign);
    grouped.push_str(&group_digits(integer, separator));
    if let Some(fraction) = fraction {
        grouped.push('.');
        grouped.push_str(fraction);
    }
    grouped.push_str(exponent);
    grouped
}

/// Insert a separator every three digits, counting from the right.
fn group_digits(digits: &str, separator: &str) -> String {
    let mut reversed = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, digit) in digits.chars().rev().enumerate() {
        if index > 0 && index % 3 == 0 {
            reversed.push_str(separator);
        }
        reversed.push(digit);
    }
    reversed.chars().rev().collect()
}

/// A date value ready for formatting.
#[cfg(feature = "dates")]
enum DateTimeValue {
    /// An instant with a time zone or a fixed offset.
    Zoned(ZonedDateTime),
    /// A date and time without a zone.
    Naive(civil::DateTime),
}

/// Parse a value as a date, a date and time, an instant or epoch seconds.
///
/// A value without an offset stays naive, so `timezone` can attach a zone
/// without shifting the clock. A value with an offset keeps it, and an epoch
/// number is read as an instant in UTC.
#[cfg(feature = "dates")]
fn parse_datetime(value: &Value) -> Result<DateTimeValue, FilterError> {
    match value {
        Value::String(text) => {
            let text = text.trim();

            if let Ok(datetime) = text.parse::<civil::DateTime>() {
                return Ok(DateTimeValue::Naive(datetime));
            }
            if let Ok(date) = text.parse::<civil::Date>() {
                return Ok(DateTimeValue::Naive(civil::DateTime::from(date)));
            }
            if let Ok(zoned) = text.parse::<ZonedDateTime>() {
                return Ok(DateTimeValue::Zoned(zoned));
            }
            if let Ok(timestamp) = text.parse::<Timestamp>() {
                return Ok(DateTimeValue::Zoned(
                    timestamp.to_zoned_datetime(TimeZone::UTC),
                ));
            }

            Err(FilterError::new(format!(
                "'{text}' is not a date; use an ISO 8601 value such as 2024-06-01T12:00:00Z"
            )))
        }
        Value::Number(number) => {
            let seconds = number
                .as_i64()
                .or_else(|| {
                    let value = number.as_f64()?;
                    (value.fract() == 0.0 && value.abs() <= 9_007_199_254_740_992.0)
                        .then_some(value as i64)
                })
                .ok_or_else(|| FilterError::new("date needs a whole number of epoch seconds"))?;

            let timestamp = Timestamp::from_second(seconds).map_err(|error| {
                FilterError::new(format!(
                    "'{seconds}' is outside the supported date range: {error}"
                ))
            })?;
            Ok(DateTimeValue::Zoned(
                timestamp.to_zoned_datetime(TimeZone::UTC),
            ))
        }
        other => Err(FilterError::new(format!(
            "date needs an ISO 8601 string or a number of epoch seconds, found {}",
            value_kind(other)
        ))),
    }
}

/// Format a date with a `strftime` style pattern.
#[cfg(feature = "dates")]
fn date(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let format = argument
        .ok_or_else(|| FilterError::new("date needs a format, for example | date: \"%Y-%m-%d\""))?;

    let formatted = match parse_datetime(value)? {
        DateTimeValue::Zoned(zoned) => strtime::format(format, &zoned),
        DateTimeValue::Naive(datetime) => strtime::format(format, datetime),
    }
    .map_err(|error| {
        FilterError::new(format!("cannot format the date with '{format}': {error}"))
    })?;

    Ok(Value::String(formatted))
}

/// Convert a date to a named time zone.
#[cfg(feature = "dates")]
fn timezone(value: &Value, argument: Option<&str>) -> Result<Value, FilterError> {
    let name = argument.ok_or_else(|| {
        FilterError::new("timezone needs a zone name, for example | timezone: \"Europe/Paris\"")
    })?;

    let zone = if name.eq_ignore_ascii_case("local") {
        TimeZone::system()
    } else {
        TimeZone::get(name)
            .map_err(|error| FilterError::new(format!("unknown time zone '{name}': {error}")))?
    };

    let zoned = match parse_datetime(value)? {
        DateTimeValue::Zoned(zoned) => zoned.with_time_zone(zone),
        DateTimeValue::Naive(datetime) => datetime.to_zoned_datetime(zone).map_err(|error| {
            FilterError::new(format!(
                "'{name}' cannot represent that local date and time: {error}"
            ))
        })?,
    };

    let text = strtime::format("%Y-%m-%dT%H:%M:%S%.f%:z", &zoned)
        .map_err(|error| FilterError::new(format!("cannot write the converted date: {error}")))?;
    Ok(Value::String(text))
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::indexing_slicing
    )]

    use super::*;
    use serde_json::json;

    fn call(registry: &FilterRegistry, name: &str, value: Value, argument: Option<&str>) -> Value {
        let filter = registry.get(name).expect("filter must exist");
        filter(&value, argument).expect("filter must succeed")
    }

    #[test]
    fn builtins_are_registered() {
        let registry = FilterRegistry::default();
        for name in ["upper", "lower", "trim", "default", "len", "join"] {
            assert!(registry.contains(name), "{name}");
        }
    }

    #[test]
    fn upper_lower_and_trim_change_text() {
        let registry = FilterRegistry::default();
        assert_eq!(call(&registry, "upper", json!("Ada"), None), json!("ADA"));
        assert_eq!(call(&registry, "lower", json!("Ada"), None), json!("ada"));
        assert_eq!(call(&registry, "trim", json!(" Ada "), None), json!("Ada"));
    }

    #[test]
    fn string_filters_format_scalars() {
        let registry = FilterRegistry::default();
        assert_eq!(call(&registry, "upper", json!(42), None), json!("42"));
        assert_eq!(call(&registry, "upper", json!(true), None), json!("TRUE"));
    }

    #[test]
    fn string_filters_reject_structured_values() {
        let registry = FilterRegistry::default();
        let filter = registry.get("upper").unwrap();
        assert!(filter(&json!([1]), None).is_err());
        assert!(filter(&json!({"a": 1}), None).is_err());
        assert!(filter(&json!(null), None).is_err());
    }

    #[test]
    fn default_replaces_null_only() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(&registry, "default", json!(null), Some("n/a")),
            json!("n/a")
        );
        assert_eq!(
            call(&registry, "default", json!("Ada"), Some("n/a")),
            json!("Ada")
        );
        assert_eq!(
            call(&registry, "default", json!(""), Some("n/a")),
            json!("")
        );
    }

    #[test]
    fn default_requires_an_argument() {
        let registry = FilterRegistry::default();
        assert!(registry.get("default").unwrap()(&json!(null), None).is_err());
    }

    #[test]
    fn len_counts_text_array_and_object() {
        let registry = FilterRegistry::default();
        assert_eq!(call(&registry, "len", json!("héllo"), None), json!(5));
        assert_eq!(call(&registry, "len", json!([1, 2, 3]), None), json!(3));
        assert_eq!(call(&registry, "len", json!({"a": 1}), None), json!(1));
        assert_eq!(call(&registry, "len", json!(null), None), json!(0));
    }

    #[test]
    fn join_uses_the_argument_as_separator() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(&registry, "join", json!(["a", "b"]), Some(" + ")),
            json!("a + b")
        );
        assert_eq!(
            call(&registry, "join", json!(["a", "b"]), None),
            json!("a, b")
        );
    }

    #[test]
    fn join_rejects_a_non_array() {
        let registry = FilterRegistry::default();
        assert!(registry.get("join").unwrap()(&json!("a"), None).is_err());
    }

    #[test]
    fn insert_replaces_a_builtin() {
        let mut registry = FilterRegistry::default();
        registry.insert("upper", |value, _| Ok(value.clone()));
        assert_eq!(call(&registry, "upper", json!("Ada"), None), json!("Ada"));
    }

    #[test]
    fn remove_reports_whether_the_filter_was_present() {
        let mut registry = FilterRegistry::default();
        assert!(registry.remove("upper"));
        assert!(!registry.remove("upper"));
        assert!(!registry.contains("upper"));
    }

    #[test]
    fn debug_lists_the_names() {
        let registry = FilterRegistry::default();
        let rendered = format!("{registry:?}");
        assert!(rendered.contains("upper"), "{rendered}");
        assert!(rendered.contains("join"), "{rendered}");
    }

    #[test]
    fn number_filters_are_registered() {
        let registry = FilterRegistry::default();
        for name in ["round", "fixed", "thousands", "percent"] {
            assert!(registry.contains(name), "{name}");
        }
    }

    #[test]
    fn round_uses_half_away_from_zero() {
        let registry = FilterRegistry::default();
        assert_eq!(call(&registry, "round", json!(2.5), None), json!(3));
        assert_eq!(call(&registry, "round", json!(-2.5), None), json!(-3));
        assert_eq!(
            call(&registry, "round", json!(1234.5678), Some("2")),
            json!(1234.57)
        );
    }

    #[test]
    fn fixed_keeps_the_requested_places() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(&registry, "fixed", json!(2.5), Some("2")),
            json!("2.50")
        );
        assert_eq!(
            call(&registry, "fixed", json!(1234.5678), Some("0")),
            json!("1235")
        );
    }

    #[test]
    fn thousands_groups_the_integer_digits() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(&registry, "thousands", json!(1234567.89), None),
            json!("1,234,567.89")
        );
        assert_eq!(
            call(&registry, "thousands", json!(-1234567), Some(" ")),
            json!("-1 234 567")
        );
        assert_eq!(
            call(&registry, "thousands", json!("1234.5"), None),
            json!("1,234.5")
        );
    }

    #[test]
    fn percent_multiplies_by_one_hundred() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(&registry, "percent", json!(0.1234), None),
            json!("12%")
        );
        assert_eq!(
            call(&registry, "percent", json!(0.1234), Some("1")),
            json!("12.3%")
        );
    }

    #[test]
    fn number_filters_reject_non_numbers() {
        let registry = FilterRegistry::default();
        for name in ["round", "fixed", "thousands", "percent"] {
            let filter = registry.get(name).unwrap();
            let argument = (name == "fixed").then_some("2");
            assert!(filter(&json!("abc"), argument).is_err(), "{name}");
            assert!(filter(&json!(true), argument).is_err(), "{name}");
            assert!(filter(&json!([1]), argument).is_err(), "{name}");
        }
    }

    #[test]
    fn number_filters_reject_too_many_places() {
        let registry = FilterRegistry::default();
        assert!(registry.get("round").unwrap()(&json!(1.5), Some("16")).is_err());
        assert!(registry.get("round").unwrap()(&json!(1.5), Some("two")).is_err());
    }

    #[cfg(feature = "dates")]
    #[test]
    fn date_filters_are_registered() {
        let registry = FilterRegistry::default();
        for name in ["date", "timezone"] {
            assert!(registry.contains(name), "{name}");
        }
    }

    #[cfg(feature = "dates")]
    #[test]
    fn date_formats_an_instant_and_a_naive_value() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(
                &registry,
                "date",
                json!("2024-06-01T12:34:56Z"),
                Some("%Y-%m-%d %H:%M")
            ),
            json!("2024-06-01 12:34")
        );
        assert_eq!(
            call(
                &registry,
                "date",
                json!("2024-06-01T12:34:56"),
                Some("%d/%m/%Y %H:%M")
            ),
            json!("01/06/2024 12:34")
        );
        assert_eq!(
            call(&registry, "date", json!("2024-06-01"), Some("%B %-d, %Y")),
            json!("June 1, 2024")
        );
    }

    #[cfg(feature = "dates")]
    #[test]
    fn date_reads_epoch_seconds() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(
                &registry,
                "date",
                json!(1_717_245_296),
                Some("%Y-%m-%dT%H:%M:%SZ")
            ),
            json!("2024-06-01T12:34:56Z")
        );
    }

    #[cfg(feature = "dates")]
    #[test]
    fn timezone_converts_an_instant() {
        let registry = FilterRegistry::default();
        let converted = call(
            &registry,
            "timezone",
            json!("2024-06-01T12:00:00Z"),
            Some("Europe/Paris"),
        );
        assert_eq!(converted, json!("2024-06-01T14:00:00+02:00"));
        assert_eq!(
            call(&registry, "date", converted, Some("%H:%M")),
            json!("14:00")
        );
    }

    #[cfg(feature = "dates")]
    #[test]
    fn timezone_attaches_a_zone_to_a_naive_value() {
        let registry = FilterRegistry::default();
        assert_eq!(
            call(
                &registry,
                "timezone",
                json!("2024-06-01T12:00:00"),
                Some("Asia/Tokyo")
            ),
            json!("2024-06-01T12:00:00+09:00")
        );
    }

    #[cfg(feature = "dates")]
    #[test]
    fn date_and_timezone_report_clear_errors() {
        let registry = FilterRegistry::default();

        let unknown =
            registry.get("timezone").unwrap()(&json!("2024-06-01T12:00:00Z"), Some("Mars/Olympus"))
                .unwrap_err();
        assert!(
            unknown.to_string().contains("unknown time zone"),
            "{unknown}"
        );

        let bad_date = registry.get("date").unwrap()(&json!("not a date"), Some("%Y")).unwrap_err();
        assert!(bad_date.to_string().contains("is not a date"), "{bad_date}");

        let missing_format = registry.get("date").unwrap()(&json!("2024-06-01"), None).unwrap_err();
        assert!(
            missing_format.to_string().contains("needs a format"),
            "{missing_format}"
        );
    }
}