uninit_read/
reflection.rs

1pub(crate) mod is_uninit_read {
2    use crate::UninitRead;
3    use std::cell::Cell;
4    use std::marker::PhantomData;
5
6    /// Checks at runtime if a type implements the [`UninitRead`] trait.
7    ///
8    /// This function allows for dynamic dispatch based on whether a reader can be
9    /// safely used with uninitialized buffers.
10    ///
11    /// The check is performed using a compile-time trick that is evaluated when the
12    /// function is instantiated for a given type `T`, but it can be called like any
13    /// normal function. It has a small runtime cost.
14    pub fn is_uninit_read<T>() -> bool {
15        struct IsUninitRead<'a, T> {
16            is_uninit_read: &'a Cell<bool>,
17            _marker: PhantomData<T>,
18        }
19
20        impl<T> Clone for IsUninitRead<'_, T> {
21            fn clone(&self) -> Self {
22                self.is_uninit_read.set(false);
23                IsUninitRead {
24                    is_uninit_read: self.is_uninit_read,
25                    _marker: PhantomData,
26                }
27            }
28        }
29        impl<T: UninitRead> Copy for IsUninitRead<'_, T> {}
30
31        let is_uninit_read = Cell::new(true);
32        let _ = [IsUninitRead::<T> {
33            is_uninit_read: &is_uninit_read,
34            _marker: PhantomData,
35        }]
36        .clone();
37        is_uninit_read.get()
38    }
39}