rootcause_internals/report/
data.rs

1//! `ReportData<C>` wrapper and field access.
2//!
3//! This module encapsulates the fields of [`ReportData`], ensuring they are
4//! only visible within this module. This visibility restriction guarantees the
5//! safety invariant: **the vtable type must always match the actual context
6//! type**.
7//!
8//! # Safety Invariant
9//!
10//! Since [`ReportData`] can only be constructed via [`ReportData::new`] (which
11//! creates matching vtable and context), and fields cannot be modified after
12//! construction (no `pub` or `pub(crate)` fields), the types remain in sync
13//! throughout the value's lifetime.
14//!
15//! # `#[repr(C)]` Layout
16//!
17//! The `#[repr(C)]` attribute enables safe field projection even when the type
18//! parameter `C` is erased. This allows accessing the vtable, children, and
19//! attachments fields from a pointer to `ReportData<Erased>` without
20//! constructing an invalid reference to the full struct.
21
22use alloc::vec::Vec;
23use core::ptr::NonNull;
24
25use crate::{
26    attachment::RawAttachment,
27    handlers::ContextHandler,
28    report::{
29        raw::{RawReport, RawReportMut, RawReportRef},
30        vtable::ReportVtable,
31    },
32    util::Erased,
33};
34
35/// Type-erased report data structure with vtable-based dispatch.
36///
37/// This struct uses `#[repr(C)]` to enable safe field access in type-erased
38/// contexts, allowing access to the vtable and other fields even when the
39/// concrete context type `C` is unknown.
40#[repr(C)]
41pub(crate) struct ReportData<C: 'static> {
42    /// Reference to the vtable of this report
43    ///
44    /// # Safety
45    ///
46    /// The following safety invariants are guaranteed to be upheld as long as
47    /// this struct exists:
48    ///
49    /// 1. The vtable must always point to a `ReportVtable` created for the
50    ///    actual context type `C` stored below. This is true even when accessed
51    ///    via type-erased pointers.
52    vtable: &'static ReportVtable,
53    /// The children of this report
54    children: Vec<RawReport>,
55    /// The attachments of this report
56    attachments: Vec<RawAttachment>,
57    /// The context data of this report
58    context: C,
59}
60
61impl<C: 'static> ReportData<C> {
62    /// Creates a new [`ReportData`] with the specified handler, context,
63    /// children and attachments.
64    ///
65    /// This method creates the vtable for type-erased dispatch and pairs it
66    /// with the report data.
67    #[inline]
68    pub(super) fn new<H: ContextHandler<C>>(
69        context: C,
70        children: Vec<RawReport>,
71        attachments: Vec<RawAttachment>,
72    ) -> Self {
73        Self {
74            vtable: ReportVtable::new::<C, H>(),
75            children,
76            attachments,
77            context,
78        }
79    }
80}
81
82impl RawReport {
83    /// Deconstructs this report into its context, children, and attachments.
84    ///
85    /// # Safety
86    ///
87    /// The caller must ensure:
88    ///
89    /// 1. The type `C` matches the actual context type stored in the
90    ///    [`ReportData`]
91    /// 2. This is the only existing reference pointing to the inner
92    ///    [`ReportData`]
93    pub unsafe fn into_parts<C: 'static>(self) -> (C, Vec<RawReport>, Vec<RawAttachment>) {
94        let ptr: NonNull<ReportData<Erased>> = self.into_non_null();
95        let ptr: NonNull<ReportData<C>> = ptr.cast::<ReportData<C>>();
96        let ptr: *const ReportData<C> = ptr.as_ptr();
97
98        // SAFETY:
99        // 1. The pointer is valid and came from `Arc::into_raw` (guaranteed by
100        //    RawReport construction)
101        // 2. After `from_raw` the `ptr` is not accessed.
102        let arc = unsafe { triomphe::Arc::<ReportData<C>>::from_raw(ptr) };
103
104        match triomphe::Arc::try_unique(arc) {
105            Ok(unique) => {
106                let data = triomphe::UniqueArc::into_inner(unique);
107                (data.context, data.children, data.attachments)
108            }
109            Err(_) => {
110                // Note: We could use `unreachable_unchecked` here in release builds for
111                // performance, but `into_parts` is not expected to be used in
112                // performance-critical paths, so a normal panic is preferable for
113                // better debugging.
114                unreachable!("Caller did not fulfill the guarantee that pointer is unique")
115            }
116        }
117    }
118}
119
120impl<'a> RawReportRef<'a> {
121    /// Returns a reference to the [`ReportVtable`] of this report.
122    ///
123    /// The returned vtable is guaranteed to match the context type stored in
124    /// the [`ReportData`].
125    #[inline]
126    pub(super) fn vtable(self) -> &'static ReportVtable {
127        let ptr = self.as_ptr();
128        // SAFETY: The safety requirements for `&raw const (*ptr).vtable` are upheld:
129        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
130        //    guaranteed by `RawReportRef`'s invariants
131        // 2. `ReportData<C>` is `#[repr(C)]`, so the `vtable` field is at a consistent
132        //    offset regardless of the type parameter `C`
133        // 3. We avoid creating a reference to the full `ReportData` struct, which would
134        //    be UB since we don't know the correct type parameter
135        let vtable_ptr: *const &'static ReportVtable = unsafe {
136            // @add-unsafe-context: ReportData
137            &raw const (*ptr).vtable
138        };
139
140        // SAFETY: The safety requirements for dereferencing `vtable_ptr` are upheld:
141        // 1. The pointer is valid and properly aligned because it points to the first
142        //    field of a valid `ReportData<C>` instance
143        // 2. The `vtable` field is initialized in `ReportData::new` and never modified,
144        //    so it contains a valid `&'static ReportVtable` value
145        unsafe { *vtable_ptr }
146    }
147
148    /// Returns the child reports of this report.
149    #[inline]
150    pub fn children(self) -> &'a Vec<RawReport> {
151        let ptr: *const ReportData<Erased> = self.as_ptr();
152
153        // SAFETY: The safety requirements for `&raw const (*ptr).children` are upheld:
154        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
155        //    guaranteed by `RawReportRef`'s invariants
156        // 2. `ReportData<C>` is `#[repr(C)]`, so the `children` field is at a
157        //    consistent offset regardless of the type parameter `C`
158        // 3. We avoid creating a reference to the full `ReportData` struct, which would
159        //    be UB since we don't know the correct type parameter
160        let children_ptr: *const Vec<RawReport> = unsafe {
161            // @add-unsafe-context: ReportData
162            &raw const (*ptr).children
163        };
164
165        // SAFETY: We turn the `*const` pointer into a `&'a` reference. This is valid
166        // because the existence of the `RawReportRef<'a>` already implies that
167        // we have readable access to the report for the 'a lifetime.
168        unsafe { &*children_ptr }
169    }
170
171    /// Returns the attachments of this report.
172    #[inline]
173    pub fn attachments(self) -> &'a Vec<RawAttachment> {
174        let ptr = self.as_ptr();
175
176        // SAFETY: The safety requirements for `&raw const (*ptr).attachments` are
177        // upheld:
178        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
179        //    guaranteed by `RawReportRef`'s invariants
180        // 2. `ReportData<C>` is `#[repr(C)]`, so the `attachments` field is at a
181        //    consistent offset regardless of the type parameter `C`
182        // 3. We avoid creating a reference to the full `ReportData` struct, which would
183        //    be UB since we don't know the correct type parameter
184        let attachments_ptr: *const Vec<RawAttachment> = unsafe {
185            // @add-unsafe-context: ReportData
186            &raw const (*ptr).attachments
187        };
188
189        // SAFETY: We turn the `*const` pointer into a `&'a` reference. This is valid
190        // because the existence of the `RawReportRef<'a>` already implies that
191        // we have readable access to the report for the 'a lifetime.
192        unsafe { &*attachments_ptr }
193    }
194
195    /// Downcasts the context to the specified type and returns a reference.
196    ///
197    /// # Safety
198    ///
199    /// The caller must ensure:
200    ///
201    /// 1. The type `C` matches the actual context type stored in the
202    ///    [`ReportData`]
203    #[inline]
204    pub unsafe fn context_downcast_unchecked<C: 'static>(self) -> &'a C {
205        // SAFETY:
206        // 1. Guaranteed by the caller
207        let this = unsafe { self.cast_inner::<C>() };
208        &this.context
209    }
210}
211
212impl<'a> RawReportMut<'a> {
213    /// Gets a mutable reference to the child reports.
214    ///
215    /// # Safety
216    ///
217    /// The caller must ensure:
218    ///
219    /// 1. In case there are other references to the same report and they make
220    ///    assumptions about the report children being `Send+Sync`, then those
221    ///    assumptions must be upheld when modifying the children.
222    #[inline]
223    pub unsafe fn into_children_mut(self) -> &'a mut Vec<RawReport> {
224        let ptr = self.into_mut_ptr();
225
226        // SAFETY: The safety requirements for `&raw mut (*ptr).children` are upheld:
227        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
228        //    guaranteed by `RawReportMut`'s invariants
229        // 2. `ReportData<C>` is `#[repr(C)]`, so the `children` field is at a
230        //    consistent offset regardless of the type parameter `C`
231        // 3. We avoid creating a reference to the full `ReportData` struct, which would
232        //    be UB since we don't know the correct type parameter
233        let children_ptr: *mut Vec<RawReport> = unsafe {
234            // @add-unsafe-context: ReportData
235            &raw mut (*ptr).children
236        };
237
238        // SAFETY: We turn the `*mut` pointer into a `&'a mut` reference. This is valid
239        // because the existence of the `RawReportMut<'a>` already implied that
240        // nobody else has mutable access to the report for the 'a lifetime.
241        unsafe { &mut *children_ptr }
242    }
243
244    /// Deconstructs the `RawReportMut` and returns a mutable reference to the
245    /// attachments vector.
246    ///
247    /// # Safety
248    ///
249    /// The caller must ensure:
250    ///
251    /// 1. In case there are other references to the same report and they make
252    ///    assumptions about the report children being `Send+Sync`, then those
253    ///    assumptions must be upheld when modifying the children.
254    #[inline]
255    pub unsafe fn into_attachments_mut(self) -> &'a mut Vec<RawAttachment> {
256        let ptr = self.into_mut_ptr();
257
258        // SAFETY: The safety requirements for `&raw mut (*ptr).attachments` are upheld:
259        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
260        //    guaranteed by `RawReportMut`'s invariants
261        // 2. `ReportData<C>` is `#[repr(C)]`, so the `attachments` field is at a
262        //    consistent offset regardless of the type parameter `C`
263        // 3. We avoid creating a reference to the full `ReportData` struct, which would
264        //    be UB since we don't know the correct type parameter
265        let attachments_ptr: *mut Vec<RawAttachment> = unsafe {
266            // @add-unsafe-context: ReportData
267            &raw mut (*ptr).attachments
268        };
269
270        // SAFETY: We turn the `*mut` pointer into a `&'a mut` reference. This is valid
271        // because the existence of the `RawReportMut<'a>` already implied that
272        // nobody else has mutable access to the report for the 'a lifetime.
273        unsafe { &mut *attachments_ptr }
274    }
275
276    /// Downcasts the context to the specified type and returns a mutable
277    /// reference.
278    ///
279    /// # Safety
280    ///
281    /// The caller must ensure:
282    ///
283    /// 1. The type `C` matches the actual context type stored in the
284    ///    [`ReportData`]
285    #[inline]
286    pub unsafe fn into_context_downcast_unchecked<C: 'static>(self) -> &'a mut C {
287        // SAFETY:
288        // 1. Guaranteed by the caller
289        let this = unsafe { self.cast_inner::<C>() };
290        &mut this.context
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn test_report_data_field_offsets() {
300        // Test that fields are accessible in the expected order for type-erased access
301        use core::mem::{offset_of, size_of};
302
303        fn check<T>() {
304            // Verify field order: vtable, children, attachments, context
305            assert_eq!(offset_of!(ReportData<T>, vtable), 0);
306            assert_eq!(
307                offset_of!(ReportData<T>, children),
308                size_of::<&'static ReportVtable>()
309            );
310            assert_eq!(
311                offset_of!(ReportData<T>, attachments),
312                size_of::<&'static ReportVtable>() + size_of::<Vec<RawAttachment>>()
313            );
314            assert!(
315                offset_of!(ReportData<T>, context)
316                    >= size_of::<&'static ReportVtable>()
317                        + size_of::<Vec<RawAttachment>>()
318                        + size_of::<Vec<RawReport>>()
319            );
320        }
321
322        #[repr(align(32))]
323        struct LargeAlignment {
324            _value: u8,
325        }
326
327        check::<u8>();
328        check::<i32>();
329        check::<[u64; 4]>();
330        check::<i32>();
331        check::<LargeAlignment>();
332    }
333}