erased_serde/
any.rs

1use crate::alloc::Box;
2#[cfg(no_maybe_uninit)]
3use core::marker::PhantomData;
4use core::mem;
5#[cfg(not(no_maybe_uninit))]
6use core::mem::MaybeUninit;
7use core::ptr;
8
9#[cfg(feature = "unstable-debug")]
10use core::any;
11
12pub struct Any {
13    value: Value,
14    drop: unsafe fn(&mut Value),
15    fingerprint: Fingerprint,
16
17    /// For panic messages only. Not used for comparison.
18    #[cfg(feature = "unstable-debug")]
19    type_name: &'static str,
20}
21
22union Value {
23    ptr: *mut (),
24    inline: [MaybeUninit<usize>; 2],
25}
26
27fn is_small<T>() -> bool {
28    cfg!(not(no_maybe_uninit))
29        && mem::size_of::<T>() <= mem::size_of::<Value>()
30        && mem::align_of::<T>() <= mem::align_of::<Value>()
31}
32
33impl Any {
34    // This is unsafe -- caller must not hold on to the Any beyond the lifetime
35    // of T.
36    //
37    // Example of bad code:
38    //
39    //    let s = "bad".to_owned();
40    //    let a = Any::new(&s);
41    //    drop(s);
42    //
43    // Now `a.view()` and `a.take()` return references to a dead String.
44    pub(crate) unsafe fn new<T>(t: T) -> Self {
45        let value: Value;
46        let drop: unsafe fn(&mut Value);
47        let fingerprint = Fingerprint::of::<T>();
48
49        if is_small::<T>() {
50            let mut inline = [MaybeUninit::uninit(); 2];
51            unsafe { ptr::write(inline.as_mut_ptr().cast::<T>(), t) };
52            value = Value { inline };
53            unsafe fn inline_drop<T>(value: &mut Value) {
54                unsafe { ptr::drop_in_place(value.inline.as_mut_ptr().cast::<T>()) }
55            }
56            drop = inline_drop::<T>;
57        } else {
58            let ptr = Box::into_raw(Box::new(t)).cast::<()>();
59            value = Value { ptr };
60            unsafe fn ptr_drop<T>(value: &mut Value) {
61                mem::drop(unsafe { Box::from_raw(value.ptr.cast::<T>()) });
62            }
63            drop = ptr_drop::<T>;
64        };
65
66        Any {
67            value,
68            drop,
69            fingerprint,
70            #[cfg(feature = "unstable-debug")]
71            type_name: any::type_name::<T>(),
72        }
73    }
74
75    // This is unsafe -- caller is responsible that T is the correct type.
76    pub(crate) unsafe fn view<T>(&mut self) -> &mut T {
77        if cfg!(not(miri)) && self.fingerprint != Fingerprint::of::<T>() {
78            self.invalid_cast_to::<T>();
79        }
80
81        let ptr = if is_small::<T>() {
82            unsafe { self.value.inline.as_mut_ptr().cast::<T>() }
83        } else {
84            unsafe { self.value.ptr.cast::<T>() }
85        };
86
87        unsafe { &mut *ptr }
88    }
89
90    // This is unsafe -- caller is responsible that T is the correct type.
91    pub(crate) unsafe fn take<T>(mut self) -> T {
92        if cfg!(not(miri)) && self.fingerprint != Fingerprint::of::<T>() {
93            self.invalid_cast_to::<T>();
94        }
95
96        if is_small::<T>() {
97            let ptr = unsafe { self.value.inline.as_mut_ptr().cast::<T>() };
98            let value = unsafe { ptr::read(ptr) };
99            mem::forget(self);
100            value
101        } else {
102            let ptr = unsafe { self.value.ptr.cast::<T>() };
103            let box_t = unsafe { Box::from_raw(ptr) };
104            mem::forget(self);
105            *box_t
106        }
107    }
108
109    #[cfg(not(feature = "unstable-debug"))]
110    fn invalid_cast_to<T>(&self) -> ! {
111        panic!("invalid cast; enable `unstable-debug` feature to debug");
112    }
113
114    #[cfg(feature = "unstable-debug")]
115    fn invalid_cast_to<T>(&self) -> ! {
116        let from = self.type_name;
117        let to = any::type_name::<T>();
118        panic!("invalid cast: {} to {}", from, to);
119    }
120}
121
122impl Drop for Any {
123    fn drop(&mut self) {
124        unsafe { (self.drop)(&mut self.value) }
125    }
126}
127
128#[cfg(no_maybe_uninit)]
129#[derive(Copy, Clone)]
130struct MaybeUninit<T>(PhantomData<T>);
131
132#[cfg(no_maybe_uninit)]
133impl<T> MaybeUninit<T> {
134    fn uninit() -> Self {
135        MaybeUninit(PhantomData)
136    }
137}
138
139#[derive(Debug, Eq, PartialEq)]
140struct Fingerprint {
141    size: usize,
142    align: usize,
143    #[cfg(include_fnptr_in_fingerprint)]
144    id: usize,
145}
146
147impl Fingerprint {
148    fn of<T>() -> Fingerprint {
149        Fingerprint {
150            size: mem::size_of::<T>(),
151            align: mem::align_of::<T>(),
152            // This is not foolproof -- theoretically Rust or LLVM could
153            // deduplicate some or all of these methods. But in practice it's
154            // great in debug mode when running our own test suite for catching
155            // bugs early.
156            #[cfg(include_fnptr_in_fingerprint)]
157            id: Fingerprint::of::<T> as usize,
158        }
159    }
160}
161
162#[test]
163fn test_fingerprint() {
164    assert_eq!(Fingerprint::of::<usize>(), Fingerprint::of::<usize>());
165    assert_eq!(Fingerprint::of::<&str>(), Fingerprint::of::<&'static str>());
166
167    assert_ne!(Fingerprint::of::<u32>(), Fingerprint::of::<[u8; 4]>());
168    assert_ne!(Fingerprint::of::<u32>(), Fingerprint::of::<[u32; 2]>());
169
170    if cfg!(all(include_fnptr_in_fingerprint, not(miri))) {
171        assert_ne!(Fingerprint::of::<usize>(), Fingerprint::of::<isize>());
172        assert_ne!(Fingerprint::of::<usize>(), Fingerprint::of::<&usize>());
173        assert_ne!(Fingerprint::of::<&usize>(), Fingerprint::of::<&&usize>());
174        assert_ne!(Fingerprint::of::<&usize>(), Fingerprint::of::<&mut usize>());
175
176        struct A;
177        struct B;
178        assert_ne!(Fingerprint::of::<A>(), Fingerprint::of::<B>());
179    }
180}