redactable 0.10.1

Automatic redaction of sensitive data in structs for safe logging and debugging
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
826
827
//! Redacted display formatting support.
//!
//! This module provides types for redacted string formatting:
//!
//! - [`RedactableWithFormatter`]: Trait for types that can format redacted display strings
//! - [`RedactedFormatterRef`]: Display wrapper that uses `fmt_redacted`
//!
//! # Passthrough Implementations
//!
//! Common scalar types implement `RedactableWithFormatter` as passthrough (unchanged output):
//! `String`, `str`, `bool`, `char`, integers, floats, `Cow<str>`, `PhantomData`, `()`.
//!
//! Container implementations format inner values recursively. `RefCell`,
//! including policy-backed formatting, uses a non-panicking borrow attempt and
//! emits `<borrowed>` on a conflicting borrow. `Mutex` and `RwLock` use
//! non-blocking lock attempts so display redaction does not wait behind a writer.
//!
//! Feature-gated types: `chrono` date/time types, `time` crate types, `Uuid`.

use std::{
    borrow::Cow,
    cmp::Ordering,
    marker::PhantomData,
    num::{
        NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
        NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
    },
    sync::{Mutex, RwLock, TryLockError},
    time::{Duration, Instant, SystemTime},
};

// =============================================================================
// RedactableWithFormatter - Trait for redacted display formatting
// =============================================================================

/// Formats a redacted string representation without requiring `Clone` or `Serialize`.
///
/// This is intended for types that want redacted logging output while keeping
/// their own `Display` implementations. Import this trait to call
/// [`redacted_display`](RedactableWithFormatter::redacted_display) on types
/// deriving `SensitiveDisplay`.
///
/// Common scalars (`String`, `bool`, integers, etc.) implement this as passthrough,
/// while types deriving `SensitiveDisplay` implement it with redaction logic.
pub trait RedactableWithFormatter {
    /// Formats a redacted representation of `self`.
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;

    /// Returns a wrapper that implements `Display` using `fmt_redacted`.
    fn redacted_display(&self) -> RedactedFormatterRef<'_, Self>
    where
        Self: Sized,
    {
        RedactedFormatterRef(self)
    }
}

// =============================================================================
// RedactedFormatterRef - Display wrapper for redacted display strings
// =============================================================================

/// Display wrapper that uses `RedactableWithFormatter::fmt_redacted`.
///
/// Returned by [`RedactableWithFormatter::redacted_display`]; implements
/// `Display` and `Debug` with the redacted representation, so it can be
/// formatted directly or converted with `.to_string()`.
pub struct RedactedFormatterRef<'a, T: ?Sized>(&'a T);

impl<T: RedactableWithFormatter + ?Sized> std::fmt::Display for RedactedFormatterRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter + ?Sized> std::fmt::Debug for RedactedFormatterRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt_redacted(f)
    }
}

/// Formatting wrapper for values after a field-level policy was applied.
///
/// Display formatting uses redacted container formatting so policy-redacted
/// containers can appear in `{field}` templates. Debug formatting stays aligned
/// with Rust's ordinary `Debug` output for the already-redacted value.
#[doc(hidden)]
pub struct PolicyRedactedFormatterRef<'a, T: ?Sized>(&'a T);

impl<'a, T: ?Sized> PolicyRedactedFormatterRef<'a, T> {
    pub fn new(value: &'a T) -> Self {
        Self(value)
    }
}

impl<T: RedactableWithFormatter + ?Sized> std::fmt::Display for PolicyRedactedFormatterRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt_redacted(f)
    }
}

impl<T: std::fmt::Debug + ?Sized> std::fmt::Debug for PolicyRedactedFormatterRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self.0, f)
    }
}

// =============================================================================
// Passthrough RedactableWithFormatter implementations
// =============================================================================

macro_rules! impl_redactable_display_passthrough {
    ($ty:ty) => {
        impl crate::redaction::display::RedactableWithFormatter for $ty {
            fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                std::fmt::Display::fmt(self, f)
            }
        }
    };
}

macro_rules! impl_redactable_display_passthrough_debug {
    ($ty:ty) => {
        impl crate::redaction::display::RedactableWithFormatter for $ty {
            fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                std::fmt::Debug::fmt(self, f)
            }
        }
    };
}

impl<T: ?Sized + RedactableWithFormatter> RedactableWithFormatter for &T {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (*self).fmt_redacted(f)
    }
}

impl_redactable_display_passthrough!(String);
impl_redactable_display_passthrough!(str);
impl_redactable_display_passthrough!(bool);
impl_redactable_display_passthrough!(char);
impl_redactable_display_passthrough!(i8);
impl_redactable_display_passthrough!(i16);
impl_redactable_display_passthrough!(i32);
impl_redactable_display_passthrough!(i64);
impl_redactable_display_passthrough!(i128);
impl_redactable_display_passthrough!(isize);
impl_redactable_display_passthrough!(u8);
impl_redactable_display_passthrough!(u16);
impl_redactable_display_passthrough!(u32);
impl_redactable_display_passthrough!(u64);
impl_redactable_display_passthrough!(u128);
impl_redactable_display_passthrough!(usize);
impl_redactable_display_passthrough!(f32);
impl_redactable_display_passthrough!(f64);
impl_redactable_display_passthrough!(Cow<'_, str>);

// NonZero integer passthrough implementations
impl_redactable_display_passthrough!(NonZeroI8);
impl_redactable_display_passthrough!(NonZeroI16);
impl_redactable_display_passthrough!(NonZeroI32);
impl_redactable_display_passthrough!(NonZeroI64);
impl_redactable_display_passthrough!(NonZeroI128);
impl_redactable_display_passthrough!(NonZeroIsize);
impl_redactable_display_passthrough!(NonZeroU8);
impl_redactable_display_passthrough!(NonZeroU16);
impl_redactable_display_passthrough!(NonZeroU32);
impl_redactable_display_passthrough!(NonZeroU64);
impl_redactable_display_passthrough!(NonZeroU128);
impl_redactable_display_passthrough!(NonZeroUsize);

// std::time and ordering passthrough implementations
impl_redactable_display_passthrough_debug!(Duration);
impl_redactable_display_passthrough_debug!(Instant);
impl_redactable_display_passthrough_debug!(SystemTime);
impl_redactable_display_passthrough_debug!(Ordering);

impl RedactableWithFormatter for () {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("()")
    }
}

impl<T> RedactableWithFormatter for PhantomData<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self, f)
    }
}

#[cfg(feature = "chrono")]
mod chrono_passthrough {
    use chrono::{
        DateTime, Duration, FixedOffset, Local, Month, NaiveDate, NaiveDateTime, NaiveTime, Utc,
        Weekday,
    };

    impl_redactable_display_passthrough!(DateTime<Utc>);
    impl_redactable_display_passthrough!(DateTime<Local>);
    impl_redactable_display_passthrough!(DateTime<FixedOffset>);
    impl_redactable_display_passthrough!(Utc);
    impl_redactable_display_passthrough!(NaiveDateTime);
    impl_redactable_display_passthrough!(NaiveDate);
    impl_redactable_display_passthrough!(NaiveTime);
    impl_redactable_display_passthrough_debug!(Duration);
    impl_redactable_display_passthrough_debug!(Month);
    impl_redactable_display_passthrough_debug!(Weekday);
}

#[cfg(feature = "time")]
mod time_passthrough {
    use time::{
        Date, Duration, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday,
    };

    impl_redactable_display_passthrough!(OffsetDateTime);
    impl_redactable_display_passthrough!(PrimitiveDateTime);
    impl_redactable_display_passthrough!(Date);
    impl_redactable_display_passthrough!(Time);
    impl_redactable_display_passthrough_debug!(Duration);
    impl_redactable_display_passthrough_debug!(UtcOffset);
    impl_redactable_display_passthrough_debug!(Month);
    impl_redactable_display_passthrough_debug!(Weekday);
}

#[cfg(feature = "uuid")]
mod uuid_passthrough {
    use uuid::Uuid;

    impl_redactable_display_passthrough!(Uuid);
}

// =============================================================================
// Container RedactableWithFormatter implementations
// =============================================================================

impl<T: RedactableWithFormatter> RedactableWithFormatter for Option<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Some(value) => f
                .debug_tuple("Some")
                .field(&value.redacted_display())
                .finish(),
            None => f.write_str("None"),
        }
    }
}

impl<T: RedactableWithFormatter> RedactableWithFormatter for Vec<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list = f.debug_list();
        for item in self {
            list.entry(&item.redacted_display());
        }
        list.finish()
    }
}

impl<T: RedactableWithFormatter> RedactableWithFormatter for [T] {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list = f.debug_list();
        for item in self {
            list.entry(&item.redacted_display());
        }
        list.finish()
    }
}

impl<T: RedactableWithFormatter, const N: usize> RedactableWithFormatter for [T; N] {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_slice().fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter> RedactableWithFormatter for std::collections::VecDeque<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list = f.debug_list();
        for item in self {
            list.entry(&item.redacted_display());
        }
        list.finish()
    }
}

impl<T0: RedactableWithFormatter> RedactableWithFormatter for (T0,) {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("(")?;
        self.0.fmt_redacted(f)?;
        f.write_str(",)")
    }
}

impl<T0: RedactableWithFormatter, T1: RedactableWithFormatter> RedactableWithFormatter
    for (T0, T1)
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("(")?;
        self.0.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.1.fmt_redacted(f)?;
        f.write_str(")")
    }
}

impl<T0: RedactableWithFormatter, T1: RedactableWithFormatter, T2: RedactableWithFormatter>
    RedactableWithFormatter for (T0, T1, T2)
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("(")?;
        self.0.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.1.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.2.fmt_redacted(f)?;
        f.write_str(")")
    }
}

impl<
    T0: RedactableWithFormatter,
    T1: RedactableWithFormatter,
    T2: RedactableWithFormatter,
    T3: RedactableWithFormatter,
> RedactableWithFormatter for (T0, T1, T2, T3)
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("(")?;
        self.0.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.1.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.2.fmt_redacted(f)?;
        f.write_str(", ")?;
        self.3.fmt_redacted(f)?;
        f.write_str(")")
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for Box<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (**self).fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for std::sync::Arc<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (**self).fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for std::rc::Rc<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (**self).fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter, E: RedactableWithFormatter> RedactableWithFormatter
    for Result<T, E>
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Ok(value) => f
                .debug_tuple("Ok")
                .field(&value.redacted_display())
                .finish(),
            Err(err) => f.debug_tuple("Err").field(&err.redacted_display()).finish(),
        }
    }
}

impl<K, V, S> RedactableWithFormatter for std::collections::HashMap<K, V, S>
where
    K: std::fmt::Debug,
    V: RedactableWithFormatter,
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut map = f.debug_map();
        for (key, value) in self {
            map.entry(key, &value.redacted_display());
        }
        map.finish()
    }
}

impl<K, V> RedactableWithFormatter for std::collections::BTreeMap<K, V>
where
    K: std::fmt::Debug,
    V: RedactableWithFormatter,
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut map = f.debug_map();
        for (key, value) in self {
            map.entry(key, &value.redacted_display());
        }
        map.finish()
    }
}

impl<T, S> RedactableWithFormatter for std::collections::HashSet<T, S>
where
    T: RedactableWithFormatter,
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut set = f.debug_set();
        for item in self {
            set.entry(&item.redacted_display());
        }
        set.finish()
    }
}

impl<T> RedactableWithFormatter for std::collections::BTreeSet<T>
where
    T: RedactableWithFormatter,
{
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut set = f.debug_set();
        for item in self {
            set.entry(&item.redacted_display());
        }
        set.finish()
    }
}

impl<T: RedactableWithFormatter + Copy> RedactableWithFormatter for std::cell::Cell<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.get().fmt_redacted(f)
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for std::cell::RefCell<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.try_borrow() {
            Ok(value) => value.fmt_redacted(f),
            Err(_) => f.write_str("<borrowed>"),
        }
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for Mutex<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.try_lock() {
            Ok(value) => value.fmt_redacted(f),
            Err(TryLockError::WouldBlock) => f.write_str("<locked>"),
            Err(TryLockError::Poisoned(err)) => err.into_inner().fmt_redacted(f),
        }
    }
}

impl<T: RedactableWithFormatter + ?Sized> RedactableWithFormatter for RwLock<T> {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.try_read() {
            Ok(value) => value.fmt_redacted(f),
            Err(TryLockError::WouldBlock) => f.write_str("<locked>"),
            Err(TryLockError::Poisoned(err)) => err.into_inner().fmt_redacted(f),
        }
    }
}

// =============================================================================
// serde_json::Value support (feature-gated)
// =============================================================================
//
// serde_json::Value always displays as "[REDACTED]" since it's an opaque type
// that could contain arbitrary sensitive data.

#[cfg(feature = "json")]
impl RedactableWithFormatter for serde_json::Value {
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[REDACTED]")
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use std::{
        cell::{Cell, RefCell},
        collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
        rc::Rc,
        sync::{Arc, Mutex, RwLock},
    };

    use super::RedactableWithFormatter;
    use crate::{Secret, SensitiveDisplay};

    #[derive(Eq, Hash, Ord, PartialEq, PartialOrd)]
    struct Key(&'static str);

    impl std::fmt::Debug for Key {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(self.0)
        }
    }

    impl RedactableWithFormatter for Key {
        fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("[REDACTED]")
        }
    }

    #[derive(SensitiveDisplay)]
    #[error("{value}")]
    struct DisplaySecret {
        #[sensitive(Secret)]
        value: String,
    }

    #[test]
    fn option_some_displays_some() {
        let opt = Some("hello".to_string());
        assert_eq!(format!("{}", opt.redacted_display()), "Some(hello)");
    }

    #[test]
    fn option_none_displays_none() {
        let opt: Option<String> = None;
        assert_eq!(format!("{}", opt.redacted_display()), "None");
    }

    #[test]
    fn vec_displays_elements() {
        let v = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert_eq!(format!("{}", v.redacted_display()), "[a, b, c]");
    }

    #[test]
    fn vec_empty_displays_brackets() {
        let v: Vec<String> = vec![];
        assert_eq!(format!("{}", v.redacted_display()), "[]");
    }

    #[test]
    fn slice_displays_elements() {
        let v = vec!["a".to_string(), "b".to_string()];
        let slice: &[String] = &v;
        assert_eq!(format!("{}", super::RedactedFormatterRef(slice)), "[a, b]");
    }

    #[test]
    fn vecdeque_displays_elements() {
        let mut v = VecDeque::new();
        v.push_back("a".to_string());
        v.push_back("b".to_string());
        assert_eq!(format!("{}", v.redacted_display()), "[a, b]");
    }

    #[test]
    fn array_displays_redacted_elements() {
        let values = [
            DisplaySecret {
                value: "first".to_string(),
            },
            DisplaySecret {
                value: "second".to_string(),
            },
        ];
        assert_eq!(
            format!("{}", values.redacted_display()),
            "[[REDACTED], [REDACTED]]"
        );
    }

    #[test]
    fn tuple_displays_redacted_elements_for_all_arities() {
        let single = (DisplaySecret {
            value: "single".to_string(),
        },);
        assert_eq!(format!("{}", single.redacted_display()), "([REDACTED],)");

        let pair = (
            DisplaySecret {
                value: "first".to_string(),
            },
            DisplaySecret {
                value: "second".to_string(),
            },
        );
        assert_eq!(
            format!("{}", pair.redacted_display()),
            "([REDACTED], [REDACTED])"
        );

        let triple = (
            DisplaySecret {
                value: "first".to_string(),
            },
            DisplaySecret {
                value: "second".to_string(),
            },
            DisplaySecret {
                value: "third".to_string(),
            },
        );
        assert_eq!(
            format!("{}", triple.redacted_display()),
            "([REDACTED], [REDACTED], [REDACTED])"
        );

        let quad = (
            DisplaySecret {
                value: "first".to_string(),
            },
            DisplaySecret {
                value: "second".to_string(),
            },
            DisplaySecret {
                value: "third".to_string(),
            },
            DisplaySecret {
                value: "fourth".to_string(),
            },
        );
        assert_eq!(
            format!("{}", quad.redacted_display()),
            "([REDACTED], [REDACTED], [REDACTED], [REDACTED])"
        );
    }

    #[test]
    fn vecdeque_policy_ref_redacts_raw_string_elements() {
        #[derive(SensitiveDisplay)]
        #[error("{values}")]
        struct WithVecDeque {
            #[sensitive(Secret)]
            values: VecDeque<String>,
        }

        let values = ["first", "second"]
            .into_iter()
            .map(str::to_string)
            .collect();
        let display = WithVecDeque { values };

        assert_eq!(
            format!("{}", display.redacted_display()),
            "[[REDACTED], [REDACTED]]"
        );
    }

    #[test]
    fn array_policy_ref_redacts_raw_string_elements() {
        #[derive(SensitiveDisplay)]
        #[error("{values}")]
        struct WithArray {
            #[sensitive(Secret)]
            values: [String; 2],
        }

        let display = WithArray {
            values: ["first".to_string(), "second".to_string()],
        };

        assert_eq!(
            format!("{}", display.redacted_display()),
            "[[REDACTED], [REDACTED]]"
        );
    }

    #[test]
    fn box_displays_inner() {
        let b = Box::new("boxed".to_string());
        assert_eq!(format!("{}", b.redacted_display()), "boxed");
    }

    #[test]
    fn arc_displays_inner() {
        let a = Arc::new("arced".to_string());
        assert_eq!(format!("{}", a.redacted_display()), "arced");
    }

    #[test]
    fn rc_displays_inner() {
        let r = Rc::new("rced".to_string());
        assert_eq!(format!("{}", r.redacted_display()), "rced");
    }

    #[test]
    fn result_ok_displays_ok() {
        let r: Result<String, String> = Ok("success".to_string());
        assert_eq!(format!("{}", r.redacted_display()), "Ok(success)");
    }

    #[test]
    fn result_err_displays_err() {
        let r: Result<String, String> = Err("failure".to_string());
        assert_eq!(format!("{}", r.redacted_display()), "Err(failure)");
    }

    #[test]
    fn btreemap_displays_entries_with_debug_keys() {
        let mut m = BTreeMap::new();
        m.insert(Key("key"), "value".to_string());
        assert_eq!(format!("{}", m.redacted_display()), "{key: value}");
    }

    #[test]
    fn btreemap_empty_displays_braces() {
        let m: BTreeMap<Key, String> = BTreeMap::new();
        assert_eq!(format!("{}", m.redacted_display()), "{}");
    }

    #[test]
    fn hashmap_displays_entries_with_debug_keys() {
        let mut m = HashMap::new();
        m.insert(Key("key"), "value".to_string());
        assert_eq!(format!("{}", m.redacted_display()), "{key: value}");
    }

    #[test]
    fn btreeset_displays_elements() {
        let mut s = BTreeSet::new();
        s.insert("a".to_string());
        s.insert("b".to_string());
        assert_eq!(format!("{}", s.redacted_display()), "{a, b}");
    }

    #[test]
    fn btreeset_empty_displays_braces() {
        let s: BTreeSet<String> = BTreeSet::new();
        assert_eq!(format!("{}", s.redacted_display()), "{}");
    }

    #[test]
    fn hashset_displays_elements() {
        let mut s = HashSet::new();
        s.insert("a".to_string());
        assert_eq!(format!("{}", s.redacted_display()), "{a}");
    }

    #[test]
    fn cell_displays_inner() {
        let c = Cell::new(42u32);
        assert_eq!(format!("{}", c.redacted_display()), "42");
    }

    #[test]
    fn refcell_displays_inner() {
        let r = RefCell::new("refcelled".to_string());
        assert_eq!(format!("{}", r.redacted_display()), "refcelled");
    }

    #[test]
    fn refcell_displays_borrowed_during_mutable_borrow() {
        let r = RefCell::new("refcelled".to_string());
        let _borrow = r.borrow_mut();
        assert_eq!(format!("{}", r.redacted_display()), "<borrowed>");
    }

    #[test]
    fn mutex_displays_redacted_inner() {
        let value = Mutex::new(DisplaySecret {
            value: "secret".to_string(),
        });
        assert_eq!(format!("{}", value.redacted_display()), "[REDACTED]");
    }

    #[test]
    fn mutex_displays_locked_on_contention() {
        let value = Mutex::new("locked".to_string());
        let _guard = value.lock().unwrap();
        assert_eq!(format!("{}", value.redacted_display()), "<locked>");
    }

    #[test]
    fn rwlock_displays_redacted_inner() {
        let value = RwLock::new(DisplaySecret {
            value: "secret".to_string(),
        });
        assert_eq!(format!("{}", value.redacted_display()), "[REDACTED]");
    }

    #[test]
    fn rwlock_displays_locked_on_contention() {
        let value = RwLock::new("locked".to_string());
        let _guard = value.write().unwrap();
        assert_eq!(format!("{}", value.redacted_display()), "<locked>");
    }

    #[test]
    fn nested_option_vec_displays() {
        let v: Vec<Option<String>> = vec![Some("a".to_string()), None, Some("c".to_string())];
        assert_eq!(
            format!("{}", v.redacted_display()),
            "[Some(a), None, Some(c)]"
        );
    }

    #[test]
    fn nested_result_in_option_displays() {
        let opt: Option<Result<String, String>> = Some(Ok("nested".to_string()));
        assert_eq!(format!("{}", opt.redacted_display()), "Some(Ok(nested))");
    }

    #[test]
    fn sensitive_display_containers_use_redacted_display() {
        #[derive(SensitiveDisplay)]
        #[error("err {message}")]
        struct MyErr {
            message: String,
        }

        #[derive(SensitiveDisplay)]
        #[error("opt={opt:?} vec={vec:?} res={res:?}")]
        struct Wrap {
            opt: Option<String>,
            vec: Vec<String>,
            res: Result<String, String>,
        }

        let err = MyErr {
            message: "boom".to_string(),
        };
        assert_eq!(format!("{}", err.redacted_display()), "err boom");

        let wrap = Wrap {
            opt: Some("opt".to_string()),
            vec: vec!["v1".to_string(), "v2".to_string()],
            res: Err("err".to_string()),
        };
        assert_eq!(
            format!("{}", wrap.redacted_display()),
            "opt=Some(opt) vec=[v1, v2] res=Err(err)"
        );
    }
}