rootcause_internals/attachment/vtable.rs
1//! Vtable for type-erased attachment operations.
2//!
3//! This module contains the [`AttachmentVtable`] which enables calling handler
4//! methods on attachments when their concrete attachment type `A` and handler
5//! type `H` have been erased. The vtable stores function pointers that dispatch
6//! to the correct typed implementations.
7//!
8//! This module encapsulates the fields of [`AttachmentVtable`] so they cannot
9//! be accessed directly. This visibility restriction guarantees the safety
10//! invariant: **the vtable's type parameters must match the actual attachment
11//! type and handler stored in the [`AttachmentData`]**.
12//!
13//! # Safety Invariant
14//!
15//! This invariant is maintained because vtables are created as `&'static`
16//! references via [`AttachmentVtable::new`], which pairs the function pointers
17//! with specific types `A` and `H` at compile time.
18
19use alloc::boxed::Box;
20use core::{any::TypeId, ptr::NonNull};
21
22use crate::{
23 attachment::{data::AttachmentData, raw::RawAttachmentRef},
24 handlers::{AttachmentFormattingStyle, AttachmentHandler, FormattingFunction},
25 util::Erased,
26};
27
28/// Vtable for type-erased attachment operations.
29///
30/// Contains function pointers for performing operations on attachments without
31/// knowing their concrete type at compile time.
32///
33/// # Safety Invariant
34///
35/// The fields `drop`, `display`, `debug`, and `preferred_formatting_style` are
36/// guaranteed to point to the functions defined below instantiated with the
37/// attachment type `A` and handler type `H` that were used to create this
38/// [`AttachmentVtable`].
39pub(crate) struct AttachmentVtable {
40 /// Gets the [`TypeId`] of the attachment type that was used to create this
41 /// [`AttachmentVtable`].
42 type_id: fn() -> TypeId,
43 /// Gets the [`TypeId`] of the handler that was used to create this
44 /// [`AttachmentVtable`].
45 handler_type_id: fn() -> TypeId,
46 /// Drops the [`Box<AttachmentData<A>>`] instance pointed to by this
47 /// pointer.
48 drop: unsafe fn(NonNull<AttachmentData<Erased>>),
49 /// Formats the attachment using the `display` method on the handler.
50 display: unsafe fn(RawAttachmentRef<'_>, &mut core::fmt::Formatter<'_>) -> core::fmt::Result,
51 /// Formats the attachment using the `debug` method on the handler.
52 debug: unsafe fn(RawAttachmentRef<'_>, &mut core::fmt::Formatter<'_>) -> core::fmt::Result,
53 /// Get the formatting style preferred by the attachment when formatted as
54 /// part of a report.
55 preferred_formatting_style:
56 unsafe fn(RawAttachmentRef<'_>, FormattingFunction) -> AttachmentFormattingStyle,
57}
58
59impl AttachmentVtable {
60 /// Creates a new [`AttachmentVtable`] for the attachment type `A` and the
61 /// handler type `H`.
62 pub(super) const fn new<A: 'static, H: AttachmentHandler<A>>() -> &'static Self {
63 const {
64 &Self {
65 type_id: TypeId::of::<A>,
66 handler_type_id: TypeId::of::<H>,
67 drop: drop::<A>,
68 display: display::<A, H>,
69 debug: debug::<A, H>,
70 preferred_formatting_style: preferred_formatting_style::<A, H>,
71 }
72 }
73 }
74
75 /// Gets the [`TypeId`] of the attachment type that was used to create this
76 /// [`AttachmentVtable`].
77 #[inline]
78 pub(super) fn type_id(&self) -> TypeId {
79 (self.type_id)()
80 }
81
82 /// Gets the [`TypeId`] of the handler that was used to create this
83 /// [`AttachmentVtable`].
84 #[inline]
85 pub(super) fn handler_type_id(&self) -> TypeId {
86 (self.handler_type_id)()
87 }
88
89 /// Drops the `Box<AttachmentData<A>>` instance pointed to by this pointer.
90 ///
91 /// # Safety
92 ///
93 /// The caller must ensure:
94 ///
95 /// 1. The pointer comes from [`Box<AttachmentData<A>>`] via
96 /// [`Box::into_raw`]
97 /// 2. This [`AttachmentVtable`] must be a vtable for the attachment type
98 /// stored in the [`RawAttachmentRef`].
99 /// 3. The pointer is not used after calling this method
100 #[inline]
101 pub(super) unsafe fn drop(&self, ptr: NonNull<AttachmentData<Erased>>) {
102 // SAFETY: We know that `self.drop` points to the function `drop::<A>` below.
103 // That function's safety requirements are upheld:
104 // 1. Guaranteed by the caller
105 // 2. Guaranteed by the caller
106 // 3. Guaranteed by the caller
107 unsafe {
108 // See https://github.com/rootcause-rs/rootcause-unsafe-analysis for details
109 // @add-unsafe-context: drop
110 (self.drop)(ptr);
111 }
112 }
113
114 /// Formats the attachment using the [`H::display`] function
115 /// used when creating this [`AttachmentVtable`].
116 ///
117 /// [`H::display`]: AttachmentHandler::display
118 ///
119 /// # Safety
120 ///
121 /// The caller must ensure:
122 ///
123 /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
124 /// stored in the [`RawAttachmentRef`].
125 #[inline]
126 pub(super) unsafe fn display(
127 &self,
128 ptr: RawAttachmentRef<'_>,
129 formatter: &mut core::fmt::Formatter<'_>,
130 ) -> core::fmt::Result {
131 // SAFETY: We know that the `self.display` field points to the function
132 // `display::<A, H>` below. That function's safety requirements are upheld:
133 // 1. Guaranteed by the caller
134 unsafe {
135 // See https://github.com/rootcause-rs/rootcause-unsafe-analysis for details
136 // @add-unsafe-context: display
137 (self.display)(ptr, formatter)
138 }
139 }
140
141 /// Formats the attachment using the [`H::debug`] function
142 /// used when creating this [`AttachmentVtable`].
143 ///
144 /// [`H::debug`]: AttachmentHandler::debug
145 ///
146 /// # Safety
147 ///
148 /// The caller must ensure:
149 ///
150 /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
151 /// stored in the [`RawAttachmentRef`].
152 #[inline]
153 pub(super) unsafe fn debug(
154 &self,
155 ptr: RawAttachmentRef<'_>,
156 formatter: &mut core::fmt::Formatter<'_>,
157 ) -> core::fmt::Result {
158 // SAFETY: We know that the `self.debug` field points to the function
159 // `debug::<A, H>` below. That function's safety requirements are upheld:
160 // 1. Guaranteed by the caller
161 unsafe {
162 // See https://github.com/rootcause-rs/rootcause-unsafe-analysis for details
163 // @add-unsafe-context: debug
164 (self.debug)(ptr, formatter)
165 }
166 }
167
168 /// Gets the preferred formatting style using the
169 /// [`H::preferred_formatting_style`] function used when creating this
170 /// [`AttachmentVtable`].
171 ///
172 /// [`H::preferred_formatting_style`]: AttachmentHandler::preferred_formatting_style
173 ///
174 /// # Safety
175 ///
176 /// The caller must ensure:
177 ///
178 /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
179 /// stored in the [`RawAttachmentRef`].
180 #[inline]
181 pub(super) unsafe fn preferred_formatting_style(
182 &self,
183 ptr: RawAttachmentRef<'_>,
184 report_formatting_function: FormattingFunction,
185 ) -> AttachmentFormattingStyle {
186 // SAFETY: We know that the `self.preferred_formatting_style` field points to
187 // the function `preferred_formatting_style::<A, H>` below. That
188 // function's safety requirements are upheld:
189 // 1. Guaranteed by the caller
190 unsafe {
191 // See https://github.com/rootcause-rs/rootcause-unsafe-analysis for details
192 // @add-unsafe-context: preferred_formatting_style
193 (self.preferred_formatting_style)(ptr, report_formatting_function)
194 }
195 }
196}
197
198/// Drops the [`Box<AttachmentData<A>>`] instance pointed to by this pointer.
199///
200/// # Safety
201///
202/// The caller must ensure:
203///
204/// 1. The pointer comes from [`Box<AttachmentData<A>>`] via [`Box::into_raw`]
205/// 2. The attachment type `A` matches the actual attachment type stored in the
206/// [`AttachmentData`]
207/// 3. The pointer is not used after calling this method
208unsafe fn drop<A: 'static>(ptr: NonNull<AttachmentData<Erased>>) {
209 let ptr: NonNull<AttachmentData<A>> = ptr.cast();
210 let ptr = ptr.as_ptr();
211 // SAFETY: Our pointer has the correct type as guaranteed by the caller, and it
212 // came from a call to `Box::into_raw` as also guaranteed by our caller.
213 let boxed = unsafe {
214 // @add-unsafe-context: AttachmentData
215 Box::from_raw(ptr)
216 };
217 core::mem::drop(boxed);
218}
219
220/// Formats an attachment using its handler's display implementation.
221///
222/// # Safety
223///
224/// The caller must ensure:
225///
226/// 1. The type `A` matches the actual attachment type stored in the
227/// [`AttachmentData`]
228unsafe fn display<A: 'static, H: AttachmentHandler<A>>(
229 ptr: RawAttachmentRef<'_>,
230 formatter: &mut core::fmt::Formatter<'_>,
231) -> core::fmt::Result {
232 // SAFETY:
233 // 1. Guaranteed by the caller
234 let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
235 H::display(attachment, formatter)
236}
237
238/// Formats an attachment using its handler's debug implementation.
239///
240/// # Safety
241///
242/// The caller must ensure:
243///
244/// 1. The type `A` matches the actual attachment type stored in the
245/// [`AttachmentData`]
246unsafe fn debug<A: 'static, H: AttachmentHandler<A>>(
247 ptr: RawAttachmentRef<'_>,
248 formatter: &mut core::fmt::Formatter<'_>,
249) -> core::fmt::Result {
250 // SAFETY:
251 // 1. Guaranteed by the caller
252 let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
253 H::debug(attachment, formatter)
254}
255
256/// Gets the preferred formatting style using the
257/// [`H::preferred_formatting_style`] function.
258///
259/// [`H::preferred_formatting_style`]: AttachmentHandler::preferred_formatting_style
260///
261/// # Safety
262///
263/// The caller must ensure:
264///
265/// 1. The type `A` matches the actual attachment type stored in the
266/// [`AttachmentData`]
267unsafe fn preferred_formatting_style<A: 'static, H: AttachmentHandler<A>>(
268 ptr: RawAttachmentRef<'_>,
269 report_formatting_function: FormattingFunction,
270) -> AttachmentFormattingStyle {
271 // SAFETY:
272 // 1. Guaranteed by the caller
273 let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
274 H::preferred_formatting_style(attachment, report_formatting_function)
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use crate::handlers::AttachmentHandler;
281
282 struct HandlerI32;
283 impl AttachmentHandler<i32> for HandlerI32 {
284 fn display(value: &i32, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
285 core::fmt::Display::fmt(value, formatter)
286 }
287
288 fn debug(value: &i32, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289 core::fmt::Debug::fmt(value, formatter)
290 }
291 }
292
293 #[test]
294 fn test_attachment_vtable_eq() {
295 // Test that vtables have proper static lifetime and can be safely shared
296 let vtable1 = AttachmentVtable::new::<i32, HandlerI32>();
297 let vtable2 = AttachmentVtable::new::<i32, HandlerI32>();
298
299 // Both should be the exact same static instance
300 assert!(core::ptr::eq(vtable1, vtable2));
301 }
302
303 #[test]
304 fn test_attachment_type_id() {
305 let vtable = AttachmentVtable::new::<i32, HandlerI32>();
306 assert_eq!(vtable.type_id(), TypeId::of::<i32>());
307 }
308}