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
/*
This module generates code to try efficiently convert some arbitrary `T: 'static` into
a `Primitive`.

In the future when `min_specialization` is stabilized we could use it instead and avoid needing
the `'static` bound altogether.
*/

use crate::internal::Primitive;

pub(super) fn from_any<'v, T: 'static>(value: &'v T) -> Option<Primitive<'v>> {
    // When we're on `nightly`, we can use const type ids
    #[cfg(value_bag_capture_const_type_id)]
    {
        use crate::std::any::TypeId;

        macro_rules! to_primitive {
            ($($ty:ty : ($const_ident:ident, $option_ident:ident),)*) => {
                trait ToPrimitive
                where
                    Self: 'static,
                {
                    const CALL: fn(&Self) -> Option<Primitive> = {
                        $(
                            const $const_ident: TypeId = TypeId::of::<$ty>();
                            const $option_ident: TypeId = TypeId::of::<Option<$ty>>();
                        )*

                        match TypeId::of::<Self>() {
                            $(
                                $const_ident => |v| Some(Primitive::from(unsafe { *(v as *const Self as *const $ty) })),
                                $option_ident => |v| Some({
                                    let v = unsafe { *(v as *const Self as *const Option<$ty>) };
                                    match v {
                                        Some(v) => Primitive::from(v),
                                        None => Primitive::None,
                                    }
                                }),
                            )*

                            _ => |_| None,
                        }
                    };

                    fn to_primitive(&self) -> Option<Primitive> {
                        (Self::CALL)(self)
                    }
                }

                impl<T: ?Sized + 'static> ToPrimitive for T {}
            }
        }

        // NOTE: The types here *must* match the ones used below when `const_type_id` is not available
        to_primitive![
            usize: (USIZE, OPTION_USIZE),
            u8: (U8, OPTION_U8),
            u16: (U16, OPTION_U16),
            u32: (U32, OPTION_U32),
            u64: (U64, OPTION_U64),
            u128: (U128, OPTION_U128),

            isize: (ISIZE, OPTION_ISIZE),
            i8: (I8, OPTION_I8),
            i16: (I16, OPTION_I16),
            i32: (I32, OPTION_I32),
            i64: (I64, OPTION_I64),
            i128: (I128, OPTION_I128),

            f32: (F32, OPTION_F32),
            f64: (F64, OPTION_F64),

            char: (CHAR, OPTION_CHAR),
            bool: (BOOL, OPTION_BOOL),
            &'static str: (STR, OPTION_STR),
        ];

        value.to_primitive()
    }

    // When we're not on `nightly`, use the ctor crate
    #[cfg(value_bag_capture_ctor)]
    {
        #![allow(unused_unsafe)]

        use ctor::ctor;

        use crate::std::{
            any::{Any, TypeId},
            cmp::Ordering,
        };

        macro_rules! type_ids {
            ($($ty:ty,)*) => {
                [
                    $(
                        (
                            std::any::TypeId::of::<$ty>(),
                            (|value| unsafe {
                                debug_assert_eq!(value.type_id(), std::any::TypeId::of::<$ty>());

                                // SAFETY: We verify the value is $ty before casting
                                let value = *(value as *const dyn std::any::Any as *const $ty);
                                Primitive::from(value)
                            }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> Primitive<'a>
                        ),
                    )*
                    $(
                        (
                            std::any::TypeId::of::<Option<$ty>>(),
                            (|value| unsafe {
                                debug_assert_eq!(value.type_id(), std::any::TypeId::of::<Option<$ty>>());

                                // SAFETY: We verify the value is Option<$ty> before casting
                                let value = *(value as *const dyn std::any::Any as *const Option<$ty>);
                                if let Some(value) = value {
                                    Primitive::from(value)
                                } else {
                                    Primitive::None
                                }
                            }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> Primitive<'a>
                        ),
                    )*
                ]
            };
        }

        // From: https://github.com/servo/rust-quicksort
        // We use this algorithm instead of the standard library's `sort_by` because it
        // works in no-std environments
        fn quicksort_helper<T, F>(arr: &mut [T], left: isize, right: isize, compare: &F)
        where
            F: Fn(&T, &T) -> Ordering,
        {
            if right <= left {
                return;
            }

            let mut i: isize = left - 1;
            let mut j: isize = right;
            let mut p: isize = i;
            let mut q: isize = j;
            unsafe {
                let v: *mut T = &mut arr[right as usize];
                loop {
                    i += 1;
                    while compare(&arr[i as usize], &*v) == Ordering::Less {
                        i += 1
                    }
                    j -= 1;
                    while compare(&*v, &arr[j as usize]) == Ordering::Less {
                        if j == left {
                            break;
                        }
                        j -= 1;
                    }
                    if i >= j {
                        break;
                    }
                    arr.swap(i as usize, j as usize);
                    if compare(&arr[i as usize], &*v) == Ordering::Equal {
                        p += 1;
                        arr.swap(p as usize, i as usize)
                    }
                    if compare(&*v, &arr[j as usize]) == Ordering::Equal {
                        q -= 1;
                        arr.swap(j as usize, q as usize)
                    }
                }
            }

            arr.swap(i as usize, right as usize);
            j = i - 1;
            i += 1;
            let mut k: isize = left;
            while k < p {
                arr.swap(k as usize, j as usize);
                k += 1;
                j -= 1;
                assert!(k < arr.len() as isize);
            }
            k = right - 1;
            while k > q {
                arr.swap(i as usize, k as usize);
                k -= 1;
                i += 1;
                assert!(k != 0);
            }

            quicksort_helper(arr, left, j, compare);
            quicksort_helper(arr, i, right, compare);
        }

        fn quicksort_by<T, F>(arr: &mut [T], compare: F)
        where
            F: Fn(&T, &T) -> Ordering,
        {
            if arr.len() <= 1 {
                return;
            }

            let len = arr.len();
            quicksort_helper(arr, 0, (len - 1) as isize, &compare);
        }

        #[ctor]
        static TYPE_IDS: [(
            TypeId,
            for<'a> fn(&'a (dyn std::any::Any + 'static)) -> Primitive<'a>,
        ); 34] = {
            // NOTE: The types here *must* match the ones used above when `const_type_id` is available
            let mut type_ids = type_ids![
                usize,
                u8,
                u16,
                u32,
                u64,
                u128,
                isize,
                i8,
                i16,
                i32,
                i64,
                i128,
                f32,
                f64,
                char,
                bool,
                &'static str,
            ];

            quicksort_by(&mut type_ids, |&(ref a, _), &(ref b, _)| a.cmp(b));

            type_ids
        };

        if let Ok(i) = TYPE_IDS.binary_search_by_key(&value.type_id(), |&(k, _)| k) {
            Some((TYPE_IDS[i].1)(value))
        } else {
            None
        }
    }

    // When we're not on `nightly` and aren't on a supported arch, we can't do capturing
    #[cfg(value_bag_capture_fallback)]
    {
        macro_rules! type_ids {
            ($($ty:ty,)*) => {
                |value| {
                    $(
                        if let Some(value) = (value as &dyn std::any::Any).downcast_ref::<$ty>() {
                            return Some(Primitive::from(*value));
                        }
                    )*
                    $(
                        if let Some(value) = (value as &dyn std::any::Any).downcast_ref::<Option<$ty>>() {
                            if let Some(value) = value {
                                return Some(Primitive::from(*value));
                            } else {
                                return Some(Primitive::None);
                            }
                        }
                    )*

                    None
                }
            };
        }

        let type_ids = type_ids![
            usize,
            u8,
            u16,
            u32,
            u64,
            u128,
            isize,
            i8,
            i16,
            i32,
            i64,
            i128,
            f32,
            f64,
            char,
            bool,
            &'static str,
        ];

        (type_ids)(value)
    }
}