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            // @add-unsafe-context: crate::util::Erased
138            &raw const (*ptr).vtable
139        };
140
141        // SAFETY: The safety requirements for dereferencing `vtable_ptr` are upheld:
142        // 1. The pointer is valid and properly aligned because it points to the first
143        //    field of a valid `ReportData<C>` instance
144        // 2. The `vtable` field is initialized in `ReportData::new` and never modified,
145        //    so it contains a valid `&'static ReportVtable` value
146        unsafe { *vtable_ptr }
147    }
148
149    /// Returns the child reports of this report.
150    #[inline]
151    pub fn children(self) -> &'a Vec<RawReport> {
152        let ptr: *const ReportData<Erased> = self.as_ptr();
153
154        // SAFETY: The safety requirements for `&raw const (*ptr).children` are upheld:
155        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
156        //    guaranteed by `RawReportRef`'s invariants
157        // 2. `ReportData<C>` is `#[repr(C)]`, so the `children` field is at a
158        //    consistent offset regardless of the type parameter `C`
159        // 3. We avoid creating a reference to the full `ReportData` struct, which would
160        //    be UB since we don't know the correct type parameter
161        let children_ptr: *const Vec<RawReport> = unsafe {
162            // @add-unsafe-context: ReportData
163            &raw const (*ptr).children
164        };
165
166        // SAFETY: We turn the `*const` pointer into a `&'a` reference. This is valid
167        // because the existence of the `RawReportRef<'a>` already implies that
168        // we have readable access to the report for the 'a lifetime.
169        unsafe { &*children_ptr }
170    }
171
172    /// Returns the attachments of this report.
173    #[inline]
174    pub fn attachments(self) -> &'a Vec<RawAttachment> {
175        let ptr = self.as_ptr();
176
177        // SAFETY: The safety requirements for `&raw const (*ptr).attachments` are
178        // upheld:
179        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
180        //    guaranteed by `RawReportRef`'s invariants
181        // 2. `ReportData<C>` is `#[repr(C)]`, so the `attachments` field is at a
182        //    consistent offset regardless of the type parameter `C`
183        // 3. We avoid creating a reference to the full `ReportData` struct, which would
184        //    be UB since we don't know the correct type parameter
185        let attachments_ptr: *const Vec<RawAttachment> = unsafe {
186            // @add-unsafe-context: ReportData
187            &raw const (*ptr).attachments
188        };
189
190        // SAFETY: We turn the `*const` pointer into a `&'a` reference. This is valid
191        // because the existence of the `RawReportRef<'a>` already implies that
192        // we have readable access to the report for the 'a lifetime.
193        unsafe { &*attachments_ptr }
194    }
195
196    /// Downcasts the context to the specified type and returns a reference.
197    ///
198    /// # Safety
199    ///
200    /// The caller must ensure:
201    ///
202    /// 1. The type `C` matches the actual context type stored in the
203    ///    [`ReportData`]
204    #[inline]
205    pub unsafe fn context_downcast_unchecked<C: 'static>(self) -> &'a C {
206        // SAFETY:
207        // 1. Guaranteed by the caller
208        let this = unsafe { self.cast_inner::<C>() };
209        &this.context
210    }
211}
212
213impl<'a> RawReportMut<'a> {
214    /// Gets a mutable reference to the child reports.
215    ///
216    /// # Safety
217    ///
218    /// The caller must ensure:
219    ///
220    /// 1. In case there are other references to the same report and they make
221    ///    assumptions about the report children being `Send+Sync`, then those
222    ///    assumptions must be upheld when modifying the children.
223    #[inline]
224    pub unsafe fn into_children_mut(self) -> &'a mut Vec<RawReport> {
225        let ptr = self.into_mut_ptr();
226
227        // SAFETY: The safety requirements for `&raw mut (*ptr).children` are upheld:
228        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
229        //    guaranteed by `RawReportMut`'s invariants
230        // 2. `ReportData<C>` is `#[repr(C)]`, so the `children` field is at a
231        //    consistent offset regardless of the type parameter `C`
232        // 3. We avoid creating a reference to the full `ReportData` struct, which would
233        //    be UB since we don't know the correct type parameter
234        let children_ptr: *mut Vec<RawReport> = unsafe {
235            // @add-unsafe-context: ReportData
236            &raw mut (*ptr).children
237        };
238
239        // SAFETY: We turn the `*mut` pointer into a `&'a mut` reference. This is valid
240        // because the existence of the `RawReportMut<'a>` already implied that
241        // nobody else has mutable access to the report for the 'a lifetime.
242        unsafe { &mut *children_ptr }
243    }
244
245    /// Deconstructs the `RawReportMut` and returns a mutable reference to the
246    /// attachments vector.
247    ///
248    /// # Safety
249    ///
250    /// The caller must ensure:
251    ///
252    /// 1. In case there are other references to the same report and they make
253    ///    assumptions about the report attachments being `Send+Sync`, then
254    ///    those assumptions must be upheld when modifying the attachments.
255    #[inline]
256    pub unsafe fn into_attachments_mut(self) -> &'a mut Vec<RawAttachment> {
257        let ptr = self.into_mut_ptr();
258
259        // SAFETY: The safety requirements for `&raw mut (*ptr).attachments` are upheld:
260        // 1. `ptr` is a valid pointer to a live `ReportData<C>` (for some `C`) as
261        //    guaranteed by `RawReportMut`'s invariants
262        // 2. `ReportData<C>` is `#[repr(C)]`, so the `attachments` field is at a
263        //    consistent offset regardless of the type parameter `C`
264        // 3. We avoid creating a reference to the full `ReportData` struct, which would
265        //    be UB since we don't know the correct type parameter
266        let attachments_ptr: *mut Vec<RawAttachment> = unsafe {
267            // @add-unsafe-context: ReportData
268            &raw mut (*ptr).attachments
269        };
270
271        // SAFETY: We turn the `*mut` pointer into a `&'a mut` reference. This is valid
272        // because the existence of the `RawReportMut<'a>` already implied that
273        // nobody else has mutable access to the report for the 'a lifetime.
274        unsafe { &mut *attachments_ptr }
275    }
276
277    /// Downcasts the context to the specified type and returns a mutable
278    /// reference.
279    ///
280    /// # Safety
281    ///
282    /// The caller must ensure:
283    ///
284    /// 1. The type `C` matches the actual context type stored in the
285    ///    [`ReportData`]
286    #[inline]
287    pub unsafe fn into_context_downcast_unchecked<C: 'static>(self) -> &'a mut C {
288        // SAFETY:
289        // 1. Guaranteed by the caller
290        let this = unsafe { self.cast_inner::<C>() };
291        &mut this.context
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn test_report_data_field_offsets() {
301        // Test that fields are accessible in the expected order for type-erased access
302        use core::mem::{offset_of, size_of};
303
304        fn check<T>() {
305            // Verify field order: vtable, children, attachments, context
306            assert_eq!(offset_of!(ReportData<T>, vtable), 0);
307            assert_eq!(
308                offset_of!(ReportData<T>, children),
309                size_of::<&'static ReportVtable>()
310            );
311            assert_eq!(
312                offset_of!(ReportData<T>, attachments),
313                size_of::<&'static ReportVtable>() + size_of::<Vec<RawAttachment>>()
314            );
315            assert!(
316                offset_of!(ReportData<T>, context)
317                    >= size_of::<&'static ReportVtable>()
318                        + size_of::<Vec<RawAttachment>>()
319                        + size_of::<Vec<RawReport>>()
320            );
321        }
322
323        #[repr(align(32))]
324        struct LargeAlignment {
325            _value: u8,
326        }
327
328        check::<u8>();
329        check::<i32>();
330        check::<[u64; 4]>();
331        check::<i32>();
332        check::<LargeAlignment>();
333    }
334}