rootcause-internals 0.13.0

Internals for the rootcause crate
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
//! Type-erased attachment pointer types.
//!
//! This module encapsulates the `ptr` field of [`RawAttachment`] and
//! [`RawAttachmentRef`], ensuring it is only visible within this module. This
//! visibility restriction guarantees the safety invariant: **the pointer always
//! comes from `Box<AttachmentData<A>>`**.
//!
//! # Safety Invariant
//!
//! Since the `ptr` field can only be set via [`RawAttachment::new`] (which
//! creates it from `Box::into_raw`), and cannot be modified afterward (no `pub`
//! or `pub(crate)` fields), the pointer provenance remains valid throughout the
//! value's lifetime.
//!
//! The [`RawAttachment::drop`] implementation relies on this invariant to
//! safely reconstruct the `Box` and deallocate the memory.
//!
//! # Type Erasure
//!
//! The concrete type parameter `A` is erased by casting to
//! `AttachmentData<Erased>`. The vtable stored within the `AttachmentData`
//! provides the runtime type information needed to safely downcast and format
//! attachments.

use alloc::boxed::Box;
use core::{
    any::{Any, TypeId},
    ptr::NonNull,
};

use crate::{
    attachment::data::AttachmentData,
    handlers::{AttachmentFormattingStyle, AttachmentHandler, FormattingFunction},
    util::Erased,
};

/// A pointer to an [`AttachmentData`] that is guaranteed to point to an
/// initialized instance of an [`AttachmentData<A>`] for some specific `A`,
/// though we do not know which actual `A` it is.
///
/// However, the pointer is allowed to transition into a non-initialized state
/// inside the [`RawAttachment::drop`] method.
///
/// The pointer is guaranteed to have been created using [`Box::into_raw`].
///
/// We cannot use a [`Box<AttachmentData<A>>`] directly, because that does not
/// allow us to type-erase the `A`.
#[repr(transparent)]
pub struct RawAttachment {
    /// Pointer to the inner attachment data
    ///
    /// # Safety
    ///
    /// The following safety invariants are guaranteed to be upheld as long as
    /// this struct exists:
    ///
    /// 1. The pointer must have been created from a `Box<AttachmentData<A>>`
    ///    for some `A` using `Box::into_raw`.
    /// 2. The pointer will point to the same `AttachmentData<A>` for the entire
    ///    lifetime of this object.
    /// 3. The pointee is properly initialized for the entire lifetime of this
    ///    object, except during the execution of the `Drop` implementation.
    /// 4. The pointer is the sole owner of the `AttachmentData` instance.
    ptr: NonNull<AttachmentData<Erased>>,
}

impl RawAttachment {
    /// Creates a new [`RawAttachment`] with the specified handler and
    /// attachment.
    ///
    /// The returned attachment will embed the specified attachment and use the
    /// specified handler for all operations.
    #[inline]
    pub fn new<A, H>(attachment: A) -> Self
    where
        A: 'static,
        H: AttachmentHandler<A>,
    {
        let ptr = Box::new(AttachmentData::new::<H>(attachment));
        let ptr: *mut AttachmentData<A> = Box::into_raw(ptr);
        let ptr: *mut AttachmentData<Erased> = ptr.cast::<AttachmentData<Erased>>();

        // SAFETY: `Box::into_raw` returns a non-null pointer
        let ptr: NonNull<AttachmentData<Erased>> = unsafe {
            // @add-unsafe-context: Erased
            NonNull::new_unchecked(ptr)
        };

        Self {
            // SAFETY:
            // 1. See above
            // 2. N/A
            // 3. N/A
            // 4. The Box is consumed, so we are the sole owner
            ptr,
        }
    }

    /// Returns a reference to the [`AttachmentData`] instance.
    #[inline]
    pub fn as_ref(&self) -> RawAttachmentRef<'_> {
        RawAttachmentRef {
            // SAFETY:
            // 1. The pointer comes from `Box::into_raw` (guaranteed by `self`'s invariant)
            // 2. We are creating the `RawAttachmentRef` here, and we are not changing the pointer
            // 3. The returned `RawAttachmentRef<'b>` represents shared access for lifetime `'b`,
            //    which is valid because we borrow `self` for `'b`, preventing any mutation through
            //    `self` while the returned reference exists
            ptr: self.ptr,
            _marker: core::marker::PhantomData,
        }
    }

    /// Returns a mutable reference to the [`AttachmentData`] instance.
    #[inline]
    pub fn as_mut(&mut self) -> RawAttachmentMut<'_> {
        RawAttachmentMut {
            // SAFETY:
            // 1. Upheld by invariant on `self`
            // 2. We are creating the `RawAttachmentMut` here, and we are not changing the pointer
            // 3. Upheld by mutable borrow of `self`
            ptr: self.ptr,
            _marker: core::marker::PhantomData,
        }
    }
}

impl core::ops::Drop for RawAttachment {
    #[inline]
    fn drop(&mut self) {
        let vtable = self.as_ref().vtable();

        // SAFETY:
        // 1. The pointer comes from `Box::into_raw` (guaranteed by
        //    `RawAttachment::new`)
        // 2. The vtable returned by `self.as_ref().vtable()` is guaranteed to match the
        //    data in the `AttachmentData`.
        // 3. The pointer is initialized and has not been previously freed as guaranteed
        //    by the invariants on this type. We are correctly transferring ownership
        //    here and the pointer is not used afterwards, as we are in the drop
        //    function.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.drop(self.ptr);
        }
    }
}

/// A lifetime-bound pointer to an [`AttachmentData`] that is guaranteed to
/// point to an initialized instance of an [`AttachmentData<A>`] for some
/// specific `A`, though we do not know which actual `A` it is.
///
/// We cannot use a [`&'a AttachmentData<A>`] directly, because that would
/// require us to know the actual type of the attachment, which we do not.
///
/// [`&'a AttachmentData<A>`]: AttachmentData
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RawAttachmentRef<'a> {
    /// Pointer to the inner attachment data
    ///
    /// # Safety
    ///
    /// The following safety invariants are guaranteed to be upheld as long as
    /// this struct exists:
    ///
    /// 1. The pointer must have been created from a `Box<AttachmentData<A>>`
    ///    for some `A` using `Box::into_raw`.
    /// 2. The pointer will point to the same `AttachmentData<A>` for the entire
    ///    lifetime of this object.
    /// 3. This pointer represents read-only access to the `AttachmentData` for
    ///    the lifetime `'a` with the same semantics as a `&'a
    ///    AttachmentData<C>`.
    ptr: NonNull<AttachmentData<Erased>>,

    /// Marker to tell the compiler that we should
    /// behave the same as a `&'a AttachmentData<Erased>`
    _marker: core::marker::PhantomData<&'a AttachmentData<Erased>>,
}

impl<'a> RawAttachmentRef<'a> {
    /// Casts the [`RawAttachmentRef`] to an [`AttachmentData<A>`] reference.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The type `A` matches the actual attachment type stored in the
    ///    [`AttachmentData`].
    #[inline]
    pub(super) unsafe fn cast_inner<A>(self) -> &'a AttachmentData<A> {
        // Debug assertion to catch type mismatches in case of bugs
        debug_assert_eq!(self.vtable().type_id(), TypeId::of::<A>());

        let this = self.ptr.cast::<AttachmentData<A>>();
        // SAFETY: Converting the NonNull pointer to a reference is sound because:
        // - The pointer is non-null, properly aligned, and dereferenceable (guaranteed
        //   by RawAttachmentRef's type invariants)
        // - The pointee is properly initialized (RawAttachmentRef's doc comment
        //   guarantees it points to an initialized AttachmentData<A> for some A)
        // - The type `A` matches the actual attachment type (guaranteed by caller)
        // - Shared access is allowed
        // - The reference lifetime 'a is valid (tied to RawAttachmentRef<'a>'s
        //   lifetime)
        unsafe { this.as_ref() }
    }

    /// Returns a [`NonNull`] pointer to the [`AttachmentData`] instance.
    #[inline]
    pub(super) fn as_ptr(self) -> *const AttachmentData<Erased> {
        self.ptr.as_ptr()
    }

    /// Returns the [`TypeId`] of the attachment.
    #[inline]
    pub fn attachment_type_id(self) -> TypeId {
        self.vtable().type_id()
    }

    /// Returns the [`core::any::type_name`] of the attachment.
    #[inline]
    pub fn attachment_type_name(self) -> &'static str {
        self.vtable().type_name()
    }

    /// Returns the [`TypeId`] of the attachment handler.
    #[inline]
    pub fn attachment_handler_type_id(self) -> TypeId {
        self.vtable().handler_type_id()
    }

    /// Formats the attachment by using the [`AttachmentHandler::display`]
    /// method specified by the handler used to create the
    /// [`AttachmentData`].
    #[inline]
    pub fn attachment_display(self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let vtable = self.vtable();
        // SAFETY:
        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
        //    the `AttachmentData`.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.display(self, formatter)
        }
    }

    /// Formats the attachment by using the [`AttachmentHandler::debug`] method
    /// specified by the handler used to create the [`AttachmentData`].
    #[inline]
    pub fn attachment_debug(self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let vtable = self.vtable();

        // SAFETY:
        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
        //    the `AttachmentData`.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.debug(self, formatter)
        }
    }

    /// Returns a [`&dyn Any`](Any) view of the attachment.
    ///
    /// The returned reference can be downcast using
    /// `<dyn Any>::downcast_ref`.
    #[inline]
    pub fn attachment_as_any(self) -> &'a (dyn Any + 'static) {
        let vtable = self.vtable();
        // SAFETY:
        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
        //    the `AttachmentData`.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.attachment_as_any(self)
        }
    }

    /// The formatting style preferred by the attachment when formatted as part
    /// of a report.
    ///
    /// # Arguments
    ///
    /// - `report_formatting_function`: Whether the report in which this
    ///   attachment will be embedded is being formatted using [`Display`]
    ///   formatting or [`Debug`]
    ///
    /// [`Display`]: core::fmt::Display
    /// [`Debug`]: core::fmt::Debug
    #[inline]
    pub fn preferred_formatting_style(
        self,
        report_formatting_function: FormattingFunction,
    ) -> AttachmentFormattingStyle {
        let vtable = self.vtable();

        // SAFETY:
        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
        //    the `AttachmentData`.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.preferred_formatting_style(self, report_formatting_function)
        }
    }
}

/// A mutable lifetime-bound pointer to an [`AttachmentData`] that is guaranteed
/// to be the sole mutable pointer to an initialized instance of an
/// [`AttachmentData<A>`] for some specific `A`, though we do not know which
/// actual `A` it is.
///
/// We cannot use a [`&'a mut AttachmentData<A>`] directly, because that would
/// require us to know the actual type of the attachment, which we do not.
///
/// [`&'a mut AttachmentData<A>`]: AttachmentData
#[repr(transparent)]
pub struct RawAttachmentMut<'a> {
    /// Pointer to the inner attachment data
    ///
    /// # Safety
    ///
    /// The following safety invariants are guaranteed to be upheld as long as
    /// this struct exists:
    ///
    /// 1. The pointer must have been created from a `Box<AttachmentData<A>>`
    ///    for some `A` using `Box::into_raw`.
    /// 2. The pointer will point to the same `AttachmentData<A>` for the entire
    ///    lifetime of this object.
    /// 3. This pointer represents exclusive mutable access to the
    ///    `AttachmentData` for the lifetime `'a` with the same semantics as a
    ///    `&'a mut AttachmentData<C>`.
    ptr: NonNull<AttachmentData<Erased>>,

    /// Marker to tell the compiler that we should
    /// behave the same as a `&'a mut AttachmentData<Erased>`
    _marker: core::marker::PhantomData<&'a mut AttachmentData<Erased>>,
}

impl<'a> RawAttachmentMut<'a> {
    /// Casts the [`RawAttachmentMut`] to an [`AttachmentData<A>`] mutable
    /// reference.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The type `A` matches the actual attachment type stored in the
    ///    [`AttachmentData`].
    #[inline]
    pub(super) unsafe fn cast_inner<A>(self) -> &'a mut AttachmentData<A> {
        // Debug assertion to catch type mismatches in case of bugs
        debug_assert_eq!(self.as_ref().vtable().type_id(), TypeId::of::<A>());

        let mut this = self.ptr.cast::<AttachmentData<A>>();
        // SAFETY: Converting the NonNull pointer to a mutable reference is sound
        // because:
        // - The pointer is non-null, properly aligned, and dereferenceable (guaranteed
        //   by RawAttachmentMut's type invariants)
        // - The pointee is properly initialized (RawAttachmentMut's doc comment
        //   guarantees it is the exclusive pointer to an initialized AttachmentData<A>
        //   for some A)
        // - The type `A` matches the actual attachment type (guaranteed by caller)
        // - Shared access is NOT allowed
        // - The reference lifetime 'a is valid (tied to RawAttachmentMut<'a>'s
        //   lifetime)
        unsafe { this.as_mut() }
    }

    /// Reborrows the mutable reference to the [`AttachmentData`] with a shorter
    /// lifetime.
    #[inline]
    pub fn reborrow<'b>(&'b mut self) -> RawAttachmentMut<'b> {
        RawAttachmentMut {
            // SAFETY:
            // 1. The pointer comes from `Box::into_raw` (guaranteed by `self`'s invariant)
            // 2. We are creating the `RawAttachmentMut` here, and we are not changing the pointer
            // 3. Exclusive mutable access for lifetime `'b` is guaranteed because:
            //    - The returned `RawAttachmentMut<'b>` contains `PhantomData<&'b mut ...>`
            //    - This causes the borrow checker to treat the return value as borrowing `self` for
            //      `'b`
            //    - Therefore `self` cannot be used while the returned value exists
            ptr: self.ptr,
            _marker: core::marker::PhantomData,
        }
    }

    /// Returns a reference to the [`AttachmentData`] instance.
    #[inline]
    pub fn as_ref<'b: 'a>(&'b self) -> RawAttachmentRef<'b> {
        RawAttachmentRef {
            // SAFETY:
            // 1. The pointer comes from `Box::into_raw` (guaranteed by `self`'s invariant)
            // 2. We are creating the `RawAttachmentRef` here, and we are not changing the pointer
            // 3. The returned `RawAttachmentRef<'b>` represents shared access for lifetime `'b`,
            //    which is valid because we borrow `self` for `'b`, preventing any mutation through
            //    `self` while the returned reference exists
            ptr: self.ptr,
            _marker: core::marker::PhantomData,
        }
    }

    /// Consumes this [`RawAttachmentMut`] and returns a [`&mut dyn Any`](Any)
    /// view of the attachment with the same lifetime.
    ///
    /// The returned reference can be downcast using
    /// `<dyn Any>::downcast_mut`.
    #[inline]
    pub fn into_attachment_as_any_mut(self) -> &'a mut (dyn Any + 'static) {
        let vtable = self.as_ref().vtable();
        // SAFETY:
        // 1. The vtable returned by `self.as_ref().vtable()` is guaranteed to match the
        //    data in the `AttachmentData`.
        unsafe {
            // @add-unsafe-context: AttachmentData
            vtable.attachment_as_any_mut(self)
        }
    }

    /// Consumes the mutable reference and returns an immutable one with the
    /// same lifetime.
    #[inline]
    pub fn into_ref(self) -> RawAttachmentRef<'a> {
        RawAttachmentRef {
            // SAFETY:
            // 1. The pointer comes from `Box::into_raw` (guaranteed by `self`'s invariant)
            // 2. We are creating the `RawAttachmentRef` here, and we are not changing the pointer
            // 3. The returned `RawAttachmentRef<'a>` represents shared access for lifetime `'a`,
            //    which is valid because we are consuming `self` and turning it into a shared
            //    reference
            ptr: self.ptr,
            _marker: core::marker::PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::String;

    use super::*;
    use crate::handlers::AttachmentHandler;

    struct HandlerI32;
    impl AttachmentHandler<i32> for HandlerI32 {
        fn display(value: &i32, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            core::fmt::Display::fmt(value, formatter)
        }

        fn debug(value: &i32, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            core::fmt::Debug::fmt(value, formatter)
        }
    }

    struct HandlerString;
    impl AttachmentHandler<String> for HandlerString {
        fn display(value: &String, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            core::fmt::Display::fmt(value, formatter)
        }

        fn debug(value: &String, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            core::fmt::Debug::fmt(value, formatter)
        }
    }

    #[test]
    fn test_raw_attachment_size() {
        assert_eq!(
            core::mem::size_of::<RawAttachment>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Option<RawAttachment>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<(), RawAttachment>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<String, RawAttachment>>(),
            core::mem::size_of::<String>()
        );
        assert_eq!(
            core::mem::size_of::<Option<Option<RawAttachment>>>(),
            core::mem::size_of::<Option<usize>>()
        );

        assert_eq!(
            core::mem::size_of::<RawAttachmentRef<'_>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Option<RawAttachmentRef<'_>>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<(), RawAttachmentRef<'_>>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<String, RawAttachmentRef<'_>>>(),
            core::mem::size_of::<String>()
        );
        assert_eq!(
            core::mem::size_of::<Option<Option<RawAttachmentRef<'_>>>>(),
            core::mem::size_of::<Option<usize>>()
        );

        assert_eq!(
            core::mem::size_of::<RawAttachmentMut<'_>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Option<RawAttachmentMut<'_>>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<(), RawAttachmentMut<'_>>>(),
            core::mem::size_of::<usize>()
        );
        assert_eq!(
            core::mem::size_of::<Result<String, RawAttachmentMut<'_>>>(),
            core::mem::size_of::<String>()
        );
        assert_eq!(
            core::mem::size_of::<Option<Option<RawAttachmentMut<'_>>>>(),
            core::mem::size_of::<Option<usize>>()
        );
    }

    #[test]
    fn test_raw_attachment_get_refs() {
        let attachment = RawAttachment::new::<i32, HandlerI32>(100);
        let attachment_ref = attachment.as_ref();

        // Accessing the pointer multiple times should be safe and consistent
        let ptr1 = attachment_ref.as_ptr();
        let ptr2 = attachment_ref.as_ptr();
        assert_eq!(ptr1, ptr2);
    }

    #[test]
    fn test_raw_attachment_downcast() {
        let int_attachment = RawAttachment::new::<i32, HandlerI32>(42);
        let string_attachment = RawAttachment::new::<String, HandlerString>(String::from("test"));

        let int_ref = int_attachment.as_ref();
        let string_ref = string_attachment.as_ref();

        // Are TypeIds what we expect?
        assert_eq!(int_ref.attachment_type_id(), TypeId::of::<i32>());
        assert_eq!(string_ref.attachment_type_id(), TypeId::of::<String>());

        // The vtables should be different
        assert!(!core::ptr::eq(int_ref.vtable(), string_ref.vtable()));
    }

    #[test]
    fn test_raw_attachment_display_debug() {
        use alloc::format;

        let int_attachment = RawAttachment::new::<i32, HandlerI32>(42);
        let string_attachment = RawAttachment::new::<String, HandlerString>(String::from("test"));

        let int_ref = int_attachment.as_ref();
        let string_ref = string_attachment.as_ref();

        // Test display formatting
        let display_int = format!(
            "{}",
            TestDisplayFormatter::new(|f| int_ref.attachment_display(f))
        );
        let display_string = format!(
            "{}",
            TestDisplayFormatter::new(|f| string_ref.attachment_display(f))
        );

        assert_eq!(display_int, "42");
        assert_eq!(display_string, "test");

        // Test debug formatting
        let debug_int = format!(
            "{}",
            TestDisplayFormatter::new(|f| int_ref.attachment_debug(f))
        );
        let debug_string = format!(
            "{}",
            TestDisplayFormatter::new(|f| string_ref.attachment_debug(f))
        );

        assert_eq!(debug_int, "42");
        assert_eq!(debug_string, "\"test\"");
    }

    // Helper struct for testing display/debug formatting
    struct TestDisplayFormatter<F> {
        formatter_fn: F,
    }

    impl<F> TestDisplayFormatter<F>
    where
        F: Fn(&mut core::fmt::Formatter<'_>) -> core::fmt::Result,
    {
        fn new(formatter_fn: F) -> Self {
            Self { formatter_fn }
        }
    }

    impl<F> core::fmt::Display for TestDisplayFormatter<F>
    where
        F: Fn(&mut core::fmt::Formatter<'_>) -> core::fmt::Result,
    {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            (self.formatter_fn)(f)
        }
    }

    #[test]
    fn test_send_sync() {
        static_assertions::assert_not_impl_any!(RawAttachment: Send, Sync);
        static_assertions::assert_not_impl_any!(RawAttachmentRef<'_>: Send, Sync);
        static_assertions::assert_not_impl_any!(RawAttachmentMut<'_>: Send, Sync);
    }

    #[test]
    fn test_raw_attachment_as_any() {
        let attachment = RawAttachment::new::<i32, HandlerI32>(42);
        let any = attachment.as_ref().attachment_as_any();
        assert_eq!(any.downcast_ref::<i32>(), Some(&42));
        assert!(any.downcast_ref::<String>().is_none());
    }

    #[test]
    fn test_raw_attachment_as_any_mut() {
        let mut attachment = RawAttachment::new::<i32, HandlerI32>(41);
        let any = attachment.as_mut().into_attachment_as_any_mut();
        *any.downcast_mut::<i32>().unwrap() += 1;
        assert_eq!(
            unsafe { *attachment.as_ref().attachment_downcast_unchecked::<i32>() },
            42
        );
    }
}