rootcause_internals/report/
raw.rs

1//! Type-erased report pointer types.
2//!
3//! This module encapsulates the `ptr` field of [`RawReport`], [`RawReportRef`],
4//! and [`RawReportMut`], ensuring it is only visible within this module. This
5//! visibility restriction guarantees the safety invariant: **the pointer always
6//! comes from `Arc<ReportData<C>>`**.
7//!
8//! # Safety Invariant
9//!
10//! Since the `ptr` field can only be set via [`RawReport::new`] or
11//! [`RawReport::from_arc`] (which create it from `Arc::into_raw`), and cannot
12//! be modified afterward (no `pub` or `pub(crate)` fields), the pointer
13//! provenance remains valid throughout the value's lifetime.
14//!
15//! The [`RawReport::drop`] implementation and reference counting operations
16//! rely on this invariant to safely reconstruct the `Arc` and manage memory.
17//!
18//! # Type Erasure
19//!
20//! The concrete type parameter `C` is erased by casting to
21//! `ReportData<Erased>`. The vtable stored within the `ReportData` provides the
22//! runtime type information needed to safely downcast and format reports.
23//!
24//! # Allocation Strategy
25//!
26//! Unlike attachments (which use `Box`), reports use `triomphe::Arc` for
27//! storage. This enables:
28//! - Cheap cloning through reference counting
29//! - Shared ownership across multiple report references
30//! - Thread-safe sharing when the context type is `Send + Sync`
31
32use alloc::vec::Vec;
33use core::{any::TypeId, ptr::NonNull};
34
35use crate::{
36    attachment::RawAttachment,
37    handlers::{ContextFormattingStyle, ContextHandler, FormattingFunction},
38    report::data::ReportData,
39    util::Erased,
40};
41
42/// A pointer to a [`ReportData`] that is guaranteed to point to an initialized
43/// instance of a [`ReportData<C>`] for some specific `C`, though we do not know
44/// which actual `C` it is.
45///
46/// However, the pointer is allowed to transition into a non-initialized state
47/// inside the [`RawReport::drop`] method.
48///
49/// The pointer is guaranteed to have been created using
50/// [`triomphe::Arc::into_raw`].
51///
52/// We cannot use a [`triomphe::OffsetArc<ReportData<C>>`] directly, because
53/// that does not allow us to type-erase the `C`.
54#[repr(transparent)]
55pub struct RawReport {
56    /// Pointer to the inner report data
57    ///
58    /// # Safety
59    ///
60    /// The following safety invariants are guaranteed to be upheld as long as
61    /// this struct exists:
62    ///
63    /// 1. The pointer must have been created from a
64    ///    `triomphe::Arc<ReportData<C>>` for some `C` using
65    ///    `triomphe::Arc::into_raw`.
66    /// 2. The pointer will point to the same `ReportData<C>` for the entire
67    ///    lifetime of this object.
68    ptr: NonNull<ReportData<Erased>>,
69}
70
71impl RawReport {
72    /// Creates a new [`RawReport`] from a [`triomphe::Arc<ReportData<C>>`].
73    #[inline]
74    pub(super) fn from_arc<C: 'static>(data: triomphe::Arc<ReportData<C>>) -> Self {
75        let ptr: *const ReportData<C> = triomphe::Arc::into_raw(data);
76        let ptr: *mut ReportData<Erased> = ptr.cast::<ReportData<Erased>>().cast_mut();
77
78        // SAFETY:
79        // 1. Triomphe guarantees that `Arc::into_raw` returns a non-null pointer.
80        let ptr: NonNull<ReportData<Erased>> = unsafe { NonNull::new_unchecked(ptr) };
81
82        Self { ptr }
83    }
84
85    /// Consumes the RawReport without decrementing the reference count and
86    /// returns the inner pointer.
87    #[inline]
88    pub(super) fn into_non_null(self) -> NonNull<ReportData<Erased>> {
89        let ptr = self.ptr;
90        core::mem::forget(self);
91        ptr
92    }
93
94    /// Creates a new [`RawReport`] with the specified handler, context,
95    /// children, and attachments.
96    ///
97    /// The created report will have the supplied context type and handler type.
98    /// It will also have a strong count of 1.
99    #[inline]
100    pub fn new<C, H>(context: C, children: Vec<RawReport>, attachments: Vec<RawAttachment>) -> Self
101    where
102        C: 'static,
103        H: ContextHandler<C>,
104    {
105        let data = triomphe::Arc::new(ReportData::new::<H>(context, children, attachments));
106        Self::from_arc(data)
107    }
108
109    /// Returns a reference to the [`ReportData`] instance.
110    #[inline]
111    pub fn as_ref(&self) -> RawReportRef<'_> {
112        RawReportRef {
113            ptr: self.ptr,
114            _marker: core::marker::PhantomData,
115        }
116    }
117
118    /// Returns a mutable reference to the [`ReportData`] instance.
119    ///
120    /// # Safety
121    ///
122    /// The caller must ensure:
123    ///
124    /// 1. This is the only existing reference pointing to the inner
125    ///    [`ReportData`]. Specifically the strong count of the inner
126    ///    [`triomphe::Arc`] must be `1`.
127    #[inline]
128    pub unsafe fn as_mut(&mut self) -> RawReportMut<'_> {
129        RawReportMut {
130            ptr: self.ptr,
131            _marker: core::marker::PhantomData,
132        }
133    }
134}
135
136impl core::ops::Drop for RawReport {
137    #[inline]
138    fn drop(&mut self) {
139        let vtable = self.as_ref().vtable();
140
141        // SAFETY:
142        // 1. The pointer comes from `Arc::into_raw` (guaranteed by `RawReport::new`)
143        // 2. The vtable returned by `self.as_ref().vtable()` is guaranteed to match the
144        //    data in the `ReportData`.
145        // 3. The pointer is not used after this call (we're in the drop function)
146        unsafe {
147            vtable.drop(self.ptr);
148        }
149    }
150}
151
152/// A lifetime-bound pointer to a [`ReportData`] that is guaranteed to point
153/// to an initialized instance of a [`ReportData<C>`] for some specific `C`,
154/// though we do not know which actual `C` it is.
155///
156/// We cannot use a [`&'a ReportData<C>`] directly, because that would require
157/// us to know the actual type of the context, which we do not.
158///
159/// [`&'a ReportData<C>`]: ReportData
160///
161/// # Safety invariants
162///
163/// This reference behaves like a `&'a ReportData<C>` for some unknown
164/// `C` and upholds the usual safety invariants of shared references:
165///
166/// 1. The pointee is properly initialized for the entire lifetime `'a`.
167/// 2. The pointee is not mutated for the entire lifetime `'a`.
168#[derive(Clone, Copy)]
169#[repr(transparent)]
170pub struct RawReportRef<'a> {
171    /// Pointer to the inner report data
172    ///
173    /// # Safety
174    ///
175    /// The following safety invariants are guaranteed to be upheld as long as
176    /// this struct exists:
177    ///
178    /// 1. The pointer must have been created from a
179    ///    `triomphe::Arc<ReportData<C>>` for some `C` using
180    ///    `triomphe::Arc::into_raw`.
181    /// 2. The pointer will point to the same `ReportData<C>` for the entire
182    ///    lifetime of this object.
183    ptr: NonNull<ReportData<Erased>>,
184
185    /// Marker to tell the compiler that we should
186    /// behave the same as a `&'a ReportData<Erased>`
187    _marker: core::marker::PhantomData<&'a ReportData<Erased>>,
188}
189
190impl<'a> RawReportRef<'a> {
191    /// Casts the [`RawReportRef`] to a [`ReportData<C>`] reference.
192    ///
193    /// # Safety
194    ///
195    /// The caller must ensure:
196    ///
197    /// 1. The type `C` matches the actual context type stored in the
198    ///    [`ReportData`]
199    #[inline]
200    pub(super) unsafe fn cast_inner<C>(self) -> &'a ReportData<C> {
201        // Debug assertion to catch type mismatches in case of bugs
202        debug_assert_eq!(self.vtable().type_id(), TypeId::of::<C>());
203
204        let this = self.ptr.cast::<ReportData<C>>();
205        // SAFETY: Converting the NonNull pointer to a reference is sound because:
206        // - The pointer is non-null, properly aligned, and dereferenceable (guaranteed
207        //   by RawReportRef's type invariants)
208        // - The pointee is properly initialized (RawReportRef's doc comment guarantees
209        //   it points to an initialized ReportData<C> for some C)
210        // - The type `C` matches the actual context type (guaranteed by caller)
211        // - Shared access is allowed
212        // - The reference lifetime 'a is valid (tied to RawReportRef<'a>'s lifetime)
213        unsafe { this.as_ref() }
214    }
215
216    /// Returns a [`NonNull`] pointer to the [`ReportData`] instance.
217    #[inline]
218    pub(super) fn as_ptr(self) -> *const ReportData<Erased> {
219        self.ptr.as_ptr()
220    }
221
222    /// Returns the [`TypeId`] of the context.
223    #[inline]
224    pub fn context_type_id(self) -> TypeId {
225        self.vtable().type_id()
226    }
227
228    /// Returns the [`TypeId`] of the context.
229    #[inline]
230    pub fn context_handler_type_id(self) -> TypeId {
231        self.vtable().handler_type_id()
232    }
233
234    /// Returns the source of the context using the [`ContextHandler::source`]
235    /// method specified when the [`ReportData`] was created.
236    #[inline]
237    pub fn context_source(self) -> Option<&'a (dyn core::error::Error + 'static)> {
238        let vtable = self.vtable();
239        // SAFETY:
240        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
241        //    the `ReportData`.
242        unsafe { vtable.source(self) }
243    }
244
245    /// Formats the context by using the [`ContextHandler::display`] method
246    /// specified by the handler used to create the [`ReportData`].
247    #[inline]
248    pub fn context_display(self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
249        let vtable = self.vtable();
250        // SAFETY:
251        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
252        //    the `ReportData`.
253        unsafe { vtable.display(self, formatter) }
254    }
255
256    /// Formats the context by using the [`ContextHandler::debug`] method
257    /// specified by the handler used to create the [`ReportData`].
258    #[inline]
259    pub fn context_debug(self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
260        let vtable = self.vtable();
261        // SAFETY:
262        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
263        //    the `ReportData`.
264        unsafe { vtable.debug(self, formatter) }
265    }
266
267    /// The formatting style preferred by the context when formatted as part of
268    /// a report.
269    ///
270    /// # Arguments
271    ///
272    /// - `report_formatting_function`: Whether the report in which this context
273    ///   will be embedded is being formatted using [`Display`] formatting or
274    ///   [`Debug`]
275    ///
276    /// [`Display`]: core::fmt::Display
277    /// [`Debug`]: core::fmt::Debug
278    #[inline]
279    pub fn preferred_context_formatting_style(
280        self,
281        report_formatting_function: FormattingFunction,
282    ) -> ContextFormattingStyle {
283        let vtable = self.vtable();
284        // SAFETY:
285        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
286        //    the `ReportData`.
287        unsafe {
288            // @add-unsafe-context: ReportData
289            vtable.preferred_context_formatting_style(self, report_formatting_function)
290        }
291    }
292
293    /// Clones the inner [`triomphe::Arc`] and returns a new [`RawReport`]
294    /// pointing to the same data.
295    ///
296    /// # Safety
297    ///
298    /// The caller must ensure:
299    ///
300    /// 1. All other references to this report are compatible with shared
301    ///    ownership. Specifically none of them assume that the strong_count is
302    ///    `1`.
303    #[inline]
304    pub unsafe fn clone_arc(self) -> RawReport {
305        let vtable = self.vtable();
306        // SAFETY:
307        // 1. Guaranteed by invariants on this type
308        // 2. Guaranteed by the fact that `ReportData` can only be constructed by
309        //    `ReportData::new`
310        // 3. Guaranteed by the caller
311        unsafe {
312            // @add-unsafe-context: ReportData
313            vtable.clone_arc(self.ptr)
314        }
315    }
316
317    /// Gets the strong_count of the inner [`triomphe::Arc`].
318    #[inline]
319    pub fn strong_count(self) -> usize {
320        let vtable = self.vtable();
321        // SAFETY:
322        // 1. The vtable returned by `self.vtable()` is guaranteed to match the data in
323        //    the `ReportData`.
324        unsafe {
325            // @add-unsafe-context: ReportData
326            vtable.strong_count(self)
327        }
328    }
329}
330
331/// A mutable lifetime-bound pointer to a [`ReportData`] that is guaranteed to
332/// point to an initialized instance of a [`ReportData<C>`] for some specific
333/// `C`, though we do not know which actual `C` it is.
334///
335/// We cannot use a [`&'a mut ReportData<C>`] directly, because that would
336/// require us to know the actual type of the context, which we do not.
337///
338/// [`&'a mut ReportData<C>`]: ReportData
339///
340/// # Safety invariants
341///
342/// This reference behaves like a `&'a mut ReportData<C>` for some unknown
343/// `C` and upholds the usual safety invariants of mutable references:
344///
345/// 1. The pointee is properly initialized for the entire lifetime `'a`.
346/// 2. The pointee is not aliased for the entire lifetime `'a`.
347/// 3. Like a `&'a mut T`, it is possible to reborrow this reference to a
348///    shorter lifetime. The borrow checker will ensure that original longer
349///    lifetime is not used while the shorter lifetime exists.
350#[repr(transparent)]
351pub struct RawReportMut<'a> {
352    /// Pointer to the inner report data
353    ///
354    /// # Safety
355    ///
356    /// The following safety invariants are guaranteed to be upheld as long as
357    /// this struct exists:
358    ///
359    /// 1. The pointer must have been created from a
360    ///    `triomphe::Arc<ReportData<C>>` for some `C` using
361    ///    `triomphe::Arc::into_raw`.
362    /// 2. The pointer will point to the same `ReportData<C>` for the entire
363    ///    lifetime of this object.
364    ptr: NonNull<ReportData<Erased>>,
365
366    /// Marker to tell the compiler that we should
367    /// behave the same as a `&'a mut ReportData<Erased>`
368    _marker: core::marker::PhantomData<&'a mut ReportData<Erased>>,
369}
370
371impl<'a> RawReportMut<'a> {
372    /// Casts the [`RawReportMut`] to a mutable [`ReportData<C>`] reference.
373    ///
374    /// # Safety
375    ///
376    /// The caller must ensure:
377    ///
378    /// 1. The type `C` matches the actual context type stored in the
379    ///    [`ReportData`]
380    #[inline]
381    pub(super) unsafe fn cast_inner<C>(self) -> &'a mut ReportData<C> {
382        // Debug assertion to catch type mismatches in case of bugs
383        debug_assert_eq!(self.as_ref().vtable().type_id(), TypeId::of::<C>());
384
385        let mut this = self.ptr.cast::<ReportData<C>>();
386
387        // SAFETY: Converting the NonNull pointer to a mutable reference is sound
388        // because:
389        // - The pointer is non-null, properly aligned, and dereferenceable (guaranteed
390        //   by RawReportMut's type invariants)
391        // - The pointee is properly initialized (RawReportMut's doc comment guarantees
392        //   it points to an initialized ReportData<C> for some C)
393        // - The type `C` matches the actual context type (guaranteed by caller)
394        // - Exclusive access is guaranteed
395        // - The reference lifetime 'a is valid (tied to RawReportMut<'a>'s lifetime)
396        unsafe { this.as_mut() }
397    }
398
399    /// Reborrows the mutable reference to the [`ReportData`] with a shorter
400    /// lifetime.
401    #[inline]
402    pub fn reborrow<'b>(&'b mut self) -> RawReportMut<'b> {
403        RawReportMut {
404            ptr: self.ptr,
405            _marker: core::marker::PhantomData,
406        }
407    }
408
409    /// Returns a reference to the [`ReportData`] instance.
410    #[inline]
411    pub fn as_ref(&self) -> RawReportRef<'_> {
412        RawReportRef {
413            ptr: self.ptr,
414            _marker: core::marker::PhantomData,
415        }
416    }
417
418    /// Consumes the mutable reference and returns an immutable one with the
419    /// same lifetime.
420    #[inline]
421    pub fn into_ref(self) -> RawReportRef<'a> {
422        RawReportRef {
423            ptr: self.ptr,
424            _marker: core::marker::PhantomData,
425        }
426    }
427
428    /// Consumes this [`RawReportMut`] and returns a raw mutable pointer to the
429    /// underlying [`ReportData`].
430    ///
431    /// This method is primarily used for internal operations that require
432    /// direct pointer access.
433    #[inline]
434    pub(super) fn into_mut_ptr(self) -> *mut ReportData<Erased> {
435        self.ptr.as_ptr()
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use alloc::{string::String, vec};
442    use core::{error::Error, fmt};
443
444    use super::*;
445    use crate::handlers::ContextHandler;
446
447    struct HandlerI32;
448    impl ContextHandler<i32> for HandlerI32 {
449        fn source(_value: &i32) -> Option<&(dyn Error + 'static)> {
450            None
451        }
452
453        fn display(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
454            fmt::Display::fmt(value, formatter)
455        }
456
457        fn debug(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
458            fmt::Debug::fmt(value, formatter)
459        }
460    }
461
462    struct HandlerString;
463    impl ContextHandler<String> for HandlerString {
464        fn source(_value: &String) -> Option<&(dyn Error + 'static)> {
465            None
466        }
467
468        fn display(value: &String, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
469            fmt::Display::fmt(value, formatter)
470        }
471
472        fn debug(value: &String, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
473            fmt::Debug::fmt(value, formatter)
474        }
475    }
476
477    #[test]
478    fn test_raw_report_size() {
479        assert_eq!(
480            core::mem::size_of::<RawReport>(),
481            core::mem::size_of::<usize>()
482        );
483        assert_eq!(
484            core::mem::size_of::<Option<RawReport>>(),
485            core::mem::size_of::<usize>()
486        );
487        assert_eq!(
488            core::mem::size_of::<Result<(), RawReport>>(),
489            core::mem::size_of::<usize>()
490        );
491        assert_eq!(
492            core::mem::size_of::<Result<String, RawReport>>(),
493            core::mem::size_of::<String>()
494        );
495        assert_eq!(
496            core::mem::size_of::<Option<Option<RawReport>>>(),
497            core::mem::size_of::<Option<usize>>()
498        );
499
500        assert_eq!(
501            core::mem::size_of::<RawReportRef<'_>>(),
502            core::mem::size_of::<usize>()
503        );
504        assert_eq!(
505            core::mem::size_of::<Option<RawReportRef<'_>>>(),
506            core::mem::size_of::<usize>()
507        );
508        assert_eq!(
509            core::mem::size_of::<Result<(), RawReportRef<'_>>>(),
510            core::mem::size_of::<usize>()
511        );
512        assert_eq!(
513            core::mem::size_of::<Result<String, RawReportRef<'_>>>(),
514            core::mem::size_of::<String>()
515        );
516        assert_eq!(
517            core::mem::size_of::<Option<Option<RawReportRef<'_>>>>(),
518            core::mem::size_of::<Option<usize>>()
519        );
520
521        assert_eq!(
522            core::mem::size_of::<RawReportMut<'_>>(),
523            core::mem::size_of::<usize>()
524        );
525        assert_eq!(
526            core::mem::size_of::<Option<RawReportMut<'_>>>(),
527            core::mem::size_of::<usize>()
528        );
529        assert_eq!(
530            core::mem::size_of::<Result<(), RawReportMut<'_>>>(),
531            core::mem::size_of::<usize>()
532        );
533        assert_eq!(
534            core::mem::size_of::<Result<String, RawReportMut<'_>>>(),
535            core::mem::size_of::<String>()
536        );
537        assert_eq!(
538            core::mem::size_of::<Option<Option<RawReportMut<'_>>>>(),
539            core::mem::size_of::<Option<usize>>()
540        );
541    }
542
543    #[test]
544    fn test_raw_report_get_refs() {
545        let report = RawReport::new::<i32, HandlerI32>(789, vec![], vec![]);
546        let report_ref = report.as_ref();
547
548        // Accessing the pointer multiple times should be safe and consistent
549        let ptr1 = report_ref.as_ptr();
550        let ptr2 = report_ref.as_ptr();
551        assert_eq!(ptr1, ptr2);
552    }
553
554    #[test]
555    fn test_raw_report_clone_arc() {
556        // Test that Arc cloning maintains safety
557        let report = RawReport::new::<i32, HandlerI32>(123, vec![], vec![]);
558        let report_ref = report.as_ref();
559
560        assert_eq!(report_ref.strong_count(), 1);
561
562        // Original should have valid data
563        assert_eq!(report_ref.context_type_id(), TypeId::of::<i32>());
564
565        // Clone should work and maintain same type
566        // SAFETY: There are no assumptions on single ownership
567        let cloned = unsafe { report_ref.clone_arc() };
568        let cloned_ref = cloned.as_ref();
569
570        assert_eq!(report_ref.strong_count(), 2);
571        assert_eq!(cloned_ref.strong_count(), 2);
572
573        // Both should have same type and vtable
574        assert_eq!(report_ref.context_type_id(), cloned_ref.context_type_id());
575        assert!(core::ptr::eq(report_ref.vtable(), cloned_ref.vtable()));
576
577        core::mem::drop(cloned);
578
579        // After dropping the strong count should go back down
580        assert_eq!(report_ref.strong_count(), 1);
581    }
582
583    #[test]
584    fn test_raw_attachment_downcast() {
585        let int_report = RawReport::new::<i32, HandlerI32>(42, vec![], vec![]);
586        let string_report =
587            RawReport::new::<String, HandlerString>(String::from("test"), vec![], vec![]);
588
589        let int_ref = int_report.as_ref();
590        let string_ref = string_report.as_ref();
591
592        // Are TypeIds what we expect?
593        assert_eq!(int_ref.context_type_id(), TypeId::of::<i32>());
594        assert_eq!(string_ref.context_type_id(), TypeId::of::<String>());
595
596        // The vtables should be different
597        assert!(!core::ptr::eq(int_ref.vtable(), string_ref.vtable()));
598
599        // Correct downcasting should work
600        assert_eq!(unsafe { int_ref.context_downcast_unchecked::<i32>() }, &42);
601        assert_eq!(
602            unsafe { string_ref.context_downcast_unchecked::<String>() },
603            "test"
604        );
605    }
606
607    #[test]
608    fn test_raw_report_children() {
609        let child = RawReport::new::<i32, HandlerI32>(1, vec![], vec![]);
610        let parent = RawReport::new::<i32, HandlerI32>(0, vec![child], vec![]);
611
612        let parent_ref = parent.as_ref();
613        assert_eq!(parent_ref.context_type_id(), TypeId::of::<i32>());
614        assert_eq!(
615            unsafe { parent_ref.context_downcast_unchecked::<i32>() },
616            &0
617        );
618
619        // Parent should have one child
620        let children = parent_ref.children();
621        assert_eq!(children.len(), 1);
622
623        // Child should be accessible safely
624        let child_ref = children[0].as_ref();
625        assert_eq!(child_ref.context_type_id(), TypeId::of::<i32>());
626        assert_eq!(child_ref.children().len(), 0);
627        assert_eq!(unsafe { child_ref.context_downcast_unchecked::<i32>() }, &1);
628
629        // Both should have same vtable (same type)
630        assert!(core::ptr::eq(parent_ref.vtable(), child_ref.vtable()));
631    }
632
633    #[test]
634    fn test_raw_report_with_attachments() {
635        use crate::{attachment::RawAttachment, handlers::AttachmentHandler};
636
637        // Create a simple attachment handler for i32
638        struct AttachmentHandlerI32;
639        impl AttachmentHandler<i32> for AttachmentHandlerI32 {
640            fn display(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
641                fmt::Display::fmt(value, formatter)
642            }
643
644            fn debug(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
645                fmt::Debug::fmt(value, formatter)
646            }
647        }
648
649        // Create some attachments
650        let attachment1 = RawAttachment::new::<i32, AttachmentHandlerI32>(100);
651        let attachment2 = RawAttachment::new::<i32, AttachmentHandlerI32>(200);
652
653        // Create a child report with one attachment
654        let child = RawReport::new::<i32, HandlerI32>(1, vec![], vec![attachment1]);
655
656        // Create a parent report with the child and another attachment
657        let parent = RawReport::new::<i32, HandlerI32>(0, vec![child], vec![attachment2]);
658
659        let parent_ref = parent.as_ref();
660        assert_eq!(parent_ref.context_type_id(), TypeId::of::<i32>());
661        assert_eq!(
662            unsafe { parent_ref.context_downcast_unchecked::<i32>() },
663            &0
664        );
665
666        // Parent should have one child and one attachment
667        let children = parent_ref.children();
668        let attachments = parent_ref.attachments();
669        assert_eq!(children.len(), 1);
670        assert_eq!(attachments.len(), 1);
671
672        // Child should be accessible safely and have one attachment
673        let child_ref = children[0].as_ref();
674        assert_eq!(child_ref.context_type_id(), TypeId::of::<i32>());
675        assert_eq!(unsafe { child_ref.context_downcast_unchecked::<i32>() }, &1);
676        assert_eq!(child_ref.children().len(), 0);
677        assert_eq!(child_ref.attachments().len(), 1);
678
679        // Check attachment downcasting works
680        let parent_attachment_ref = attachments[0].as_ref();
681        let child_attachment_ref = child_ref.attachments()[0].as_ref();
682
683        assert_eq!(
684            parent_attachment_ref.attachment_type_id(),
685            TypeId::of::<i32>()
686        );
687        assert_eq!(
688            child_attachment_ref.attachment_type_id(),
689            TypeId::of::<i32>()
690        );
691
692        // Downcast attachments and verify values
693        assert_eq!(
694            unsafe { *parent_attachment_ref.attachment_downcast_unchecked::<i32>() },
695            200
696        );
697        assert_eq!(
698            unsafe { *child_attachment_ref.attachment_downcast_unchecked::<i32>() },
699            100
700        );
701
702        // Both reports should have same vtable (same context type)
703        assert!(core::ptr::eq(parent_ref.vtable(), child_ref.vtable()));
704    }
705
706    #[test]
707    fn test_raw_report_mut_basic() {
708        let mut report = RawReport::new::<i32, HandlerI32>(789, vec![], vec![]);
709
710        // SAFETY: We have unique ownership of the report
711        let mut report_mut = unsafe { report.as_mut() };
712
713        // Test that we can get a reference from the mutable reference
714        let report_ref = report_mut.as_ref();
715        assert_eq!(report_ref.context_type_id(), TypeId::of::<i32>());
716        assert_eq!(
717            unsafe { report_ref.context_downcast_unchecked::<i32>() },
718            &789
719        );
720
721        // Test reborrow functionality
722        let reborrowed = report_mut.reborrow();
723        let ref_from_reborrow = reborrowed.as_ref();
724        assert_eq!(ref_from_reborrow.context_type_id(), TypeId::of::<i32>());
725        assert_eq!(
726            unsafe { ref_from_reborrow.context_downcast_unchecked::<i32>() },
727            &789
728        );
729
730        // Test into_mut_ptr
731        let ptr = report_mut.into_mut_ptr();
732        assert!(!ptr.is_null());
733    }
734
735    #[test]
736    fn test_raw_report_mut_reborrow_lifetime() {
737        let mut report =
738            RawReport::new::<String, HandlerString>(String::from("test"), vec![], vec![]);
739
740        // SAFETY: We have unique ownership of the report
741        let mut report_mut = unsafe { report.as_mut() };
742
743        // Test that reborrow works with different lifetimes
744        {
745            let short_reborrow = report_mut.reborrow();
746            let ref_from_short = short_reborrow.as_ref();
747            assert_eq!(ref_from_short.context_type_id(), TypeId::of::<String>());
748            assert_eq!(
749                unsafe { ref_from_short.context_downcast_unchecked::<String>() },
750                "test"
751            );
752        }
753
754        // Original mutable reference should still be usable
755        let final_ref = report_mut.as_ref();
756        assert_eq!(final_ref.context_type_id(), TypeId::of::<String>());
757        assert_eq!(
758            unsafe { final_ref.context_downcast_unchecked::<String>() },
759            "test"
760        );
761    }
762
763    #[test]
764    fn test_raw_report_mut_with_children() {
765        let child = RawReport::new::<i32, HandlerI32>(1, vec![], vec![]);
766        let mut parent = RawReport::new::<i32, HandlerI32>(0, vec![child], vec![]);
767
768        // SAFETY: We have unique ownership of the parent report
769        let mut parent_mut = unsafe { parent.as_mut() };
770
771        let parent_ref = parent_mut.as_ref();
772        assert_eq!(parent_ref.context_type_id(), TypeId::of::<i32>());
773        assert_eq!(
774            unsafe { parent_ref.context_downcast_unchecked::<i32>() },
775            &0
776        );
777
778        // Check that children are still accessible through the reference
779        let children = parent_ref.children();
780        assert_eq!(children.len(), 1);
781
782        let child_ref = children[0].as_ref();
783        assert_eq!(child_ref.context_type_id(), TypeId::of::<i32>());
784        assert_eq!(unsafe { child_ref.context_downcast_unchecked::<i32>() }, &1);
785
786        // Test reborrow with children
787        let reborrowed = parent_mut.reborrow();
788        let reborrow_ref = reborrowed.as_ref();
789        let reborrow_children = reborrow_ref.children();
790        assert_eq!(reborrow_children.len(), 1);
791        assert_eq!(
792            reborrow_children[0].as_ref().context_type_id(),
793            TypeId::of::<i32>()
794        );
795        assert_eq!(
796            unsafe {
797                reborrow_children[0]
798                    .as_ref()
799                    .context_downcast_unchecked::<i32>()
800            },
801            &1
802        );
803    }
804
805    #[test]
806    fn test_raw_report_mut_ptr_consistency() {
807        let mut report = RawReport::new::<i32, HandlerI32>(42, vec![], vec![]);
808
809        // Get immutable reference pointer first
810        let immut_ref = report.as_ref();
811        let immut_ptr = immut_ref.as_ptr();
812        // SAFETY: We have unique ownership of the report
813        let report_mut = unsafe { report.as_mut() };
814
815        // Get mutable pointer
816        let mut_ptr = report_mut.into_mut_ptr();
817
818        // Both pointers should point to the same location
819        assert_eq!(immut_ptr, mut_ptr as *const _);
820    }
821    #[test]
822    fn test_send_sync() {
823        static_assertions::assert_not_impl_any!(RawReport: Send, Sync);
824        static_assertions::assert_not_impl_any!(RawReportRef<'_>: Send, Sync);
825        static_assertions::assert_not_impl_any!(RawReportMut<'_>: Send, Sync);
826    }
827}