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
use std::{any::TypeId, borrow::Cow};
pub fn cast_vec<T: Copy>(mut vec: Vec<T>) -> Vec<u8> {
let len = std::mem::size_of::<T>() * vec.len();
let cap = std::mem::size_of::<T>() * vec.capacity();
let ptr = vec.as_mut_ptr();
std::mem::forget(vec);
unsafe { Vec::from_raw_parts(ptr as _, len, cap) }
}
pub fn cast_slice<T>(slice: &[T]) -> &[u8] {
let len = std::mem::size_of::<T>() * slice.len();
let ptr = slice.as_ptr();
unsafe { std::slice::from_raw_parts(ptr as _, len) }
}
pub fn cast_cow<T: Copy>(cow: Cow<'_, [T]>) -> Cow<'_, [u8]> {
match cow {
Cow::Borrowed(slice) => Cow::Borrowed(cast_slice(slice)),
Cow::Owned(vec) => Cow::Owned(cast_vec(vec)),
}
}
pub fn identical_cast<T: 'static, U: 'static>(value: T) -> U {
assert_eq!(TypeId::of::<T>(), TypeId::of::<U>());
unsafe {
let mut value = std::mem::ManuallyDrop::new(value);
let ptr: *mut T = &mut *value;
std::ptr::read(ptr as *mut U)
}
}