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
//! Vtable for type-erased attachment operations.
//!
//! This module contains the [`AttachmentVtable`] which enables calling handler
//! methods on attachments when their concrete attachment type `A` and handler
//! type `H` have been erased. The vtable stores function pointers that dispatch
//! to the correct typed implementations.
//!
//! This module encapsulates the fields of [`AttachmentVtable`] so they cannot
//! be accessed directly. This visibility restriction guarantees the safety
//! invariant: **the vtable's type parameters must match the actual attachment
//! type and handler stored in the [`AttachmentData`]**.
//!
//! # Safety Invariant
//!
//! This invariant is maintained because vtables are created as `&'static`
//! references via [`AttachmentVtable::new`], which pairs the function pointers
//! with specific types `A` and `H` at compile time.

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

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

/// Vtable for type-erased attachment operations.
///
/// Contains function pointers for performing operations on attachments without
/// knowing their concrete type at compile time.
///
/// # Safety Invariant
///
/// The fields `drop`, `display`, `debug`, and `preferred_formatting_style` are
/// guaranteed to point to the functions defined below instantiated with the
/// attachment type `A` and handler type `H` that were used to create this
/// [`AttachmentVtable`].
pub(crate) struct AttachmentVtable {
    /// Gets the [`TypeId`] of the attachment type that was used to create this
    /// [`AttachmentVtable`].
    type_id: fn() -> TypeId,
    /// Gets the [`any::type_name`] of the attachment type that was used to
    /// create this [`AttachmentVtable`].
    type_name: fn() -> &'static str,
    /// Gets the [`TypeId`] of the handler that was used to create this
    /// [`AttachmentVtable`].
    handler_type_id: fn() -> TypeId,
    /// Drops the [`Box<AttachmentData<A>>`] instance pointed to by this
    /// pointer.
    drop: unsafe fn(NonNull<AttachmentData<Erased>>),
    /// Formats the attachment using the `display` method on the handler.
    display: unsafe fn(RawAttachmentRef<'_>, &mut core::fmt::Formatter<'_>) -> core::fmt::Result,
    /// Formats the attachment using the `debug` method on the handler.
    debug: unsafe fn(RawAttachmentRef<'_>, &mut core::fmt::Formatter<'_>) -> core::fmt::Result,
    /// Get the formatting style preferred by the attachment when formatted as
    /// part of a report.
    preferred_formatting_style:
        unsafe fn(RawAttachmentRef<'_>, FormattingFunction) -> AttachmentFormattingStyle,
    /// Returns a `&dyn Any` view of the attachment.
    attachment_as_any: unsafe fn(RawAttachmentRef<'_>) -> &(dyn Any + 'static),
    /// Returns a `&mut dyn Any` view of the attachment.
    attachment_as_any_mut: unsafe fn(RawAttachmentMut<'_>) -> &mut (dyn Any + 'static),
}

impl AttachmentVtable {
    /// Creates a new [`AttachmentVtable`] for the attachment type `A` and the
    /// handler type `H`.
    pub(super) const fn new<A: 'static, H: AttachmentHandler<A>>() -> &'static Self {
        const {
            &Self {
                type_id: TypeId::of::<A>,
                type_name: any::type_name::<A>,
                handler_type_id: TypeId::of::<H>,
                drop: drop::<A>,
                display: display::<A, H>,
                debug: debug::<A, H>,
                preferred_formatting_style: preferred_formatting_style::<A, H>,
                attachment_as_any: attachment_as_any::<A>,
                attachment_as_any_mut: attachment_as_any_mut::<A>,
            }
        }
    }

    /// Gets the [`TypeId`] of the attachment type that was used to create this
    /// [`AttachmentVtable`].
    #[inline]
    pub(super) fn type_id(&self) -> TypeId {
        (self.type_id)()
    }

    /// Gets the [`any::type_name`] of the attachment type that was used to
    /// create this [`AttachmentVtable`].
    #[inline]
    pub(super) fn type_name(&self) -> &'static str {
        (self.type_name)()
    }

    /// Gets the [`TypeId`] of the handler that was used to create this
    /// [`AttachmentVtable`].
    #[inline]
    pub(super) fn handler_type_id(&self) -> TypeId {
        (self.handler_type_id)()
    }

    /// Drops the `Box<AttachmentData<A>>` instance pointed to by this pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The pointer comes from [`Box<AttachmentData<A>>`] via
    ///    [`Box::into_raw`]
    /// 2. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`AttachmentData`].
    /// 3. This method drops the [`Box<AttachmentData<A>>`], so the caller must
    ///    ensure that the pointer has not previously been dropped, that it is
    ///    able to transfer ownership of the pointer, and that it will not use
    ///    the pointer after calling this method.
    #[inline]
    pub(super) unsafe fn drop(&self, ptr: NonNull<AttachmentData<Erased>>) {
        // SAFETY: We know that `self.drop` points to the function `drop::<A>` below.
        // That function's safety requirements are upheld:
        // 1. Guaranteed by the caller
        // 2. Guaranteed by the caller
        // 3. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: drop
            (self.drop)(ptr);
        }
    }

    /// Formats the attachment using the [`H::display`] function
    /// used when creating this [`AttachmentVtable`].
    ///
    /// [`H::display`]: AttachmentHandler::display
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`RawAttachmentRef`].
    #[inline]
    pub(super) unsafe fn display(
        &self,
        ptr: RawAttachmentRef<'_>,
        formatter: &mut core::fmt::Formatter<'_>,
    ) -> core::fmt::Result {
        // SAFETY: We know that the `self.display` field points to the function
        // `display::<A, H>` below. That function's safety requirements are upheld:
        // 1. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: display
            (self.display)(ptr, formatter)
        }
    }

    /// Formats the attachment using the [`H::debug`] function
    /// used when creating this [`AttachmentVtable`].
    ///
    /// [`H::debug`]: AttachmentHandler::debug
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`RawAttachmentRef`].
    #[inline]
    pub(super) unsafe fn debug(
        &self,
        ptr: RawAttachmentRef<'_>,
        formatter: &mut core::fmt::Formatter<'_>,
    ) -> core::fmt::Result {
        // SAFETY: We know that the `self.debug` field points to the function
        // `debug::<A, H>` below. That function's safety requirements are upheld:
        // 1. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: debug
            // @add-unsafe-context: RawAttachmentRef
            // @add-unsafe-context: AttachmentData
            (self.debug)(ptr, formatter)
        }
    }

    /// Gets the preferred formatting style using the
    /// [`H::preferred_formatting_style`] function used when creating this
    /// [`AttachmentVtable`].
    ///
    /// [`H::preferred_formatting_style`]: AttachmentHandler::preferred_formatting_style
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`RawAttachmentRef`].
    #[inline]
    pub(super) unsafe fn preferred_formatting_style(
        &self,
        ptr: RawAttachmentRef<'_>,
        report_formatting_function: FormattingFunction,
    ) -> AttachmentFormattingStyle {
        // SAFETY: We know that the `self.preferred_formatting_style` field points to
        // the function `preferred_formatting_style::<A, H>` below. That
        // function's safety requirements are upheld:
        // 1. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: preferred_formatting_style
            // @add-unsafe-context: RawAttachmentRef
            // @add-unsafe-context: AttachmentData
            (self.preferred_formatting_style)(ptr, report_formatting_function)
        }
    }

    /// Returns a `&dyn Any` reference to the attachment using the function
    /// pointer stored in this [`AttachmentVtable`].
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`RawAttachmentRef`].
    #[inline]
    pub(super) unsafe fn attachment_as_any<'a>(
        &self,
        ptr: RawAttachmentRef<'a>,
    ) -> &'a (dyn Any + 'static) {
        // SAFETY: We know that the `self.attachment_as_any` field points to the
        // function `attachment_as_any::<A>` below. That function's safety
        // requirements are upheld:
        // 1. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: attachment_as_any
            // @add-unsafe-context: RawAttachmentRef
            // @add-unsafe-context: AttachmentData
            (self.attachment_as_any)(ptr)
        }
    }

    /// Returns a `&mut dyn Any` reference to the attachment using the function
    /// pointer stored in this [`AttachmentVtable`].
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. This [`AttachmentVtable`] must be a vtable for the attachment type
    ///    stored in the [`RawAttachmentMut`].
    #[inline]
    pub(super) unsafe fn attachment_as_any_mut<'a>(
        &self,
        ptr: RawAttachmentMut<'a>,
    ) -> &'a mut (dyn Any + 'static) {
        // SAFETY: We know that the `self.attachment_as_any_mut` field points to
        // the function `attachment_as_any_mut::<A>` below. That function's
        // safety requirements are upheld:
        // 1. Guaranteed by the caller
        unsafe {
            // @add-unsafe-context: attachment_as_any_mut
            // @add-unsafe-context: RawAttachmentMut
            // @add-unsafe-context: AttachmentData
            (self.attachment_as_any_mut)(ptr)
        }
    }
}

/// Drops the [`Box<AttachmentData<A>>`] instance pointed to by this pointer.
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The pointer comes from [`Box<AttachmentData<A>>`] via [`Box::into_raw`]
/// 2. The attachment type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
/// 3. This method drops the [`Box<AttachmentData<A>>`], so the caller must
///    ensure that the pointer has not previously been dropped, that it is able
///    to transfer ownership of the pointer, and that it will not use the
///    pointer after calling this method.
unsafe fn drop<A: 'static>(ptr: NonNull<AttachmentData<Erased>>) {
    let ptr: NonNull<AttachmentData<A>> = ptr.cast();
    let ptr = ptr.as_ptr();
    // SAFETY: Our pointer has the correct type as guaranteed by the caller, and it
    // came from a call to `Box::into_raw` as also guaranteed by our caller.
    let boxed = unsafe {
        // @add-unsafe-context: AttachmentData
        Box::from_raw(ptr)
    };
    core::mem::drop(boxed);
}

/// Formats an attachment using its handler's display implementation.
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
unsafe fn display<A: 'static, H: AttachmentHandler<A>>(
    ptr: RawAttachmentRef<'_>,
    formatter: &mut core::fmt::Formatter<'_>,
) -> core::fmt::Result {
    // SAFETY:
    // 1. Guaranteed by the caller
    let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
    H::display(attachment, formatter)
}

/// Formats an attachment using its handler's debug implementation.
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
unsafe fn debug<A: 'static, H: AttachmentHandler<A>>(
    ptr: RawAttachmentRef<'_>,
    formatter: &mut core::fmt::Formatter<'_>,
) -> core::fmt::Result {
    // SAFETY:
    // 1. Guaranteed by the caller
    let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
    H::debug(attachment, formatter)
}

/// Gets the preferred formatting style using the
/// [`H::preferred_formatting_style`] function.
///
/// [`H::preferred_formatting_style`]: AttachmentHandler::preferred_formatting_style
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
unsafe fn preferred_formatting_style<A: 'static, H: AttachmentHandler<A>>(
    ptr: RawAttachmentRef<'_>,
    report_formatting_function: FormattingFunction,
) -> AttachmentFormattingStyle {
    // SAFETY:
    // 1. Guaranteed by the caller
    let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
    H::preferred_formatting_style(attachment, report_formatting_function)
}

/// Returns a `&dyn Any` view of the attachment.
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
unsafe fn attachment_as_any<'a, A: 'static>(ptr: RawAttachmentRef<'a>) -> &'a (dyn Any + 'static) {
    // SAFETY:
    // 1. Guaranteed by the caller
    let attachment: &A = unsafe { ptr.attachment_downcast_unchecked::<A>() };
    attachment as &(dyn Any + 'static)
}

/// Returns a `&mut dyn Any` view of the attachment.
///
/// # Safety
///
/// The caller must ensure:
///
/// 1. The type `A` matches the actual attachment type stored in the
///    [`AttachmentData`]
unsafe fn attachment_as_any_mut<'a, A: 'static>(
    ptr: RawAttachmentMut<'a>,
) -> &'a mut (dyn Any + 'static) {
    // SAFETY:
    // 1. Guaranteed by the caller
    let attachment: &mut A = unsafe { ptr.into_attachment_downcast_unchecked::<A>() };
    attachment as &mut (dyn Any + 'static)
}

#[cfg(test)]
mod tests {
    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)
        }
    }

    #[test]
    fn test_attachment_vtable_eq() {
        // Test that vtables have proper static lifetime and can be safely shared
        let vtable1 = AttachmentVtable::new::<i32, HandlerI32>();
        let vtable2 = AttachmentVtable::new::<i32, HandlerI32>();

        // Both should be the exact same static instance
        assert!(core::ptr::eq(vtable1, vtable2));
    }

    #[test]
    fn test_attachment_type_id() {
        let vtable = AttachmentVtable::new::<i32, HandlerI32>();
        assert_eq!(vtable.type_id(), TypeId::of::<i32>());
    }

    #[test]
    fn test_attachment_type_name() {
        let vtable = AttachmentVtable::new::<i32, HandlerI32>();
        assert_eq!(vtable.type_name(), core::any::type_name::<i32>());
    }
}