Skip to main content

rten_base/
byte_cast.rs

1//! Cast values and slices to/from bytes.
2
3use std::alloc::Layout;
4use std::mem::{ManuallyDrop, MaybeUninit};
5
6/// Types which can be transmuted to a byte array.
7///
8/// # Safety
9///
10/// This type must only be implemented for `Copy` types which contain no
11/// padding.
12pub unsafe trait ToByteArray: Copy {
13    /// Array of bytes whose length is equal to the alignment of the type.
14    type Align: AsRef<[u8]>;
15
16    /// View of this type as an array of bytes.
17    type Bytes: AsRef<[u8]>;
18
19    /// Convert this type to an array of bytes in native order.
20    ///
21    /// This is the same as `to_ne_bytes` for primitive types.
22    fn to_bytes(self) -> Self::Bytes;
23}
24
25macro_rules! impl_to_byte_array {
26    ($type:ty) => {
27        unsafe impl ToByteArray for $type {
28            type Align = [u8; align_of::<$type>()];
29            type Bytes = [u8; size_of::<$type>()];
30
31            fn to_bytes(self) -> Self::Bytes {
32                self.to_ne_bytes()
33            }
34        }
35    };
36}
37
38impl_to_byte_array!(i8);
39impl_to_byte_array!(u8);
40impl_to_byte_array!(i16);
41impl_to_byte_array!(u16);
42impl_to_byte_array!(i32);
43impl_to_byte_array!(u32);
44impl_to_byte_array!(i64);
45impl_to_byte_array!(u64);
46impl_to_byte_array!(f32);
47impl_to_byte_array!(f64);
48
49unsafe impl ToByteArray for bool {
50    type Align = [u8; 1];
51    type Bytes = [u8; 1];
52
53    fn to_bytes(self) -> [u8; 1] {
54        [self as u8]
55    }
56}
57
58/// Types which can be transmuted from a byte array.
59///
60/// These are types for which any bit pattern is valid.
61///
62/// # Safety
63///
64/// This type must only be implemented for types for which any bit pattern is
65/// valid.
66pub unsafe trait FromByteArray: ToByteArray {
67    /// Convert an array of bytes, in native order, into this type.
68    ///
69    /// This is the same as `from_ne_bytes` for primitive types.
70    fn from_bytes(bytes: Self::Bytes) -> Self;
71
72    /// Convert this type to another of the same size.
73    ///
74    /// This should compile to a zero-cost transmute.
75    fn cast_bytes<Dst>(self) -> Dst
76    where
77        Dst: FromByteArray<Bytes = Self::Bytes>,
78    {
79        Dst::from_bytes(self.to_bytes())
80    }
81}
82
83macro_rules! impl_from_byte_array {
84    ($type:ty) => {
85        unsafe impl FromByteArray for $type {
86            fn from_bytes(val: Self::Bytes) -> Self {
87                Self::from_ne_bytes(val)
88            }
89        }
90    };
91}
92
93impl_from_byte_array!(i8);
94impl_from_byte_array!(u8);
95impl_from_byte_array!(i16);
96impl_from_byte_array!(u16);
97impl_from_byte_array!(i32);
98impl_from_byte_array!(u32);
99impl_from_byte_array!(i64);
100impl_from_byte_array!(u64);
101impl_from_byte_array!(f32);
102impl_from_byte_array!(f64);
103
104/// Return the length of a slice transmuted from `Src` to `Dst`, or `None` if
105/// the transmute is not possible.
106fn transmuted_slice_len<Src, Dst>(src: &[Src]) -> Option<usize> {
107    if !(src.as_ptr() as usize).is_multiple_of(align_of::<Dst>()) {
108        return None;
109    }
110
111    let src_byte_len = std::mem::size_of_val(src);
112    if !src_byte_len.is_multiple_of(size_of::<Dst>()) {
113        return None;
114    }
115
116    Some(src_byte_len / size_of::<Dst>())
117}
118
119/// Transmute a slice of elements from one type to another.
120///
121/// This cast is safe because all bytes of the source elements are initialized
122/// and all bit patterns are valid for the destination elements.
123///
124/// Returns `None` if the source pointer is not correctly aligned for the
125/// destination type.
126pub fn cast_slice<Src: ToByteArray, Dst: FromByteArray>(src: &[Src]) -> Option<&[Dst]> {
127    // Containers which have not allocated use a dangling pointer aligned for
128    // `Src`, which may not be aligned for `Dst`.
129    if src.is_empty() {
130        return Some(&[]);
131    }
132
133    let new_len = transmuted_slice_len::<_, Dst>(src)?;
134
135    // Safety:
136    // - Pointer cast is safe since any bit pattern is valid for POD types
137    // - Length has been adjusted for `Dst` type
138    Some(unsafe { std::slice::from_raw_parts(src.as_ptr() as *const Dst, new_len) })
139}
140
141/// Transmute a mutable slice of elements from one type to another.
142///
143/// This cast is safe because all bytes of the source elements are initialized
144/// and all bit patterns are valid for the destination elements.
145///
146/// Returns `None` if the source pointer is not correctly aligned for the
147/// destination type.
148#[allow(unused)]
149pub fn cast_mut_slice<Src: ToByteArray, Dst: FromByteArray>(src: &mut [Src]) -> Option<&mut [Dst]> {
150    // Containers which have not allocated use a dangling pointer aligned for
151    // `Src`, which may not be aligned for `Dst`.
152    if src.is_empty() {
153        return Some(&mut []);
154    }
155
156    let new_len = transmuted_slice_len::<_, Dst>(src)?;
157
158    // Safety:
159    // - Pointer cast is safe since any bit pattern is valid for POD types
160    // - Length has been adjusted for `Dst` type
161    Some(unsafe { std::slice::from_raw_parts_mut(src.as_mut_ptr() as *mut Dst, new_len) })
162}
163
164/// Transmute a mutable slice of elements from one uninitialized type to another.
165///
166/// Returns `None` if the source pointer is not correctly aligned for the
167/// destination type.
168pub fn cast_uninit_mut_slice<Src: ToByteArray, Dst: FromByteArray>(
169    src: &mut [MaybeUninit<Src>],
170) -> Option<&mut [MaybeUninit<Dst>]> {
171    // Containers which have not allocated use a dangling pointer aligned for
172    // `Src`, which may not be aligned for `Dst`.
173    if src.is_empty() {
174        return Some(&mut []);
175    }
176
177    let new_len = transmuted_slice_len::<_, Dst>(src)?;
178
179    // Safety:
180    // - Pointer cast is safe since any bit pattern is valid for POD types
181    // - Length has been adjusted for `Dst` type
182    Some(unsafe {
183        std::slice::from_raw_parts_mut(src.as_mut_ptr() as *mut MaybeUninit<Dst>, new_len)
184    })
185}
186
187/// Transmute a vector of elements from one type to another.
188///
189/// The source and destination types must have the same size and alignment.
190/// The length and capacity of the vector will be the same afterwards.
191pub fn cast_vec<Src: ToByteArray, Dst: FromByteArray>(src: Vec<Src>) -> Option<Vec<Dst>> {
192    // A vector which has not allocated owns no buffer to transmute, and its
193    // dangling pointer is aligned for `Src` rather than `Dst`.
194    if src.capacity() == 0 {
195        return Some(Vec::new());
196    }
197
198    // From `Vec::into_raw_parts`.
199    let mut src = ManuallyDrop::new(src);
200    let (src_ptr, src_len, src_cap) = (src.as_mut_ptr(), src.len(), src.capacity());
201
202    if Layout::array::<Src>(src_cap) != Layout::array::<Dst>(src_cap) {
203        return None;
204    }
205
206    // Safety: `Src` and `Dest` types have the same layout for an array of
207    // `src_cap` elements, so the allocation is compatible, all bytes of `Src`
208    // are initialized and any bit pattern is valid as a value of `Dst`.
209    Some(unsafe { Vec::from_raw_parts(src_ptr as *mut Dst, src_len, src_cap) })
210}
211
212/// Types which can be viewed as a slice of bytes.
213///
214/// # Safety
215///
216/// To implement this trait, types must:
217///
218/// - Have a defined layout (eg. using `#[repr(C)]`)
219/// - Contain no padding bytes or other uninitialized bytes
220/// - Contain no interior mutability
221pub unsafe trait AsBytes: Sized {
222    /// Transmute a reference to a byte slice.
223    fn as_bytes(&self) -> &[u8] {
224        unsafe { std::slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>()) }
225    }
226
227    /// Transmute a value to a signed byte slice.
228    fn as_signed_bytes(&self) -> &[i8] {
229        unsafe { std::slice::from_raw_parts(self as *const Self as *const i8, size_of::<Self>()) }
230    }
231}
232
233/// Types which can be transmuted from a slice of bytes.
234///
235/// # Safety
236///
237/// To implement this trait, types must:
238///
239/// - Allow all bit patterns
240/// - Contain no interior mutability
241pub unsafe trait FromBytes: Sized {
242    /// Transmute a reference to a byte slice into a reference to this type.
243    ///
244    /// Panics of the size or alignment of the slice does not match that required
245    /// for `self`.
246    fn from_bytes(bytes: &[u8]) -> &Self {
247        assert!(
248            bytes.len() == size_of::<Self>()
249                && (bytes.as_ptr() as usize).is_multiple_of(align_of::<Self>())
250        );
251        unsafe { &*bytes.as_ptr().cast::<Self>() }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use std::mem::MaybeUninit;
258
259    use super::{
260        AsBytes, FromByteArray, FromBytes, cast_mut_slice, cast_slice, cast_uninit_mut_slice,
261        cast_vec,
262    };
263
264    #[test]
265    fn test_cast_bytes() {
266        let float_val = 1.2f32;
267        let int_val: i32 = float_val.cast_bytes();
268        assert_eq!(int_val, i32::from_ne_bytes(float_val.to_ne_bytes()));
269    }
270
271    #[test]
272    fn test_cast_slice() {
273        // Convert to narrower type
274        let i32s = [1, 2, 3];
275        let i8s = cast_slice::<i32, i8>(&i32s).unwrap();
276        assert_eq!(i8s.as_ptr(), i32s.as_ptr() as *const i8);
277        assert_eq!(i8s.len(), i32s.len() * 4);
278
279        // Convert back to wider type
280        let i32s_v2 = cast_slice::<i8, i32>(i8s).unwrap();
281        assert_eq!(i32s_v2, i32s);
282    }
283
284    #[test]
285    fn test_cast_empty() {
286        // An empty `Vec` uses a dangling pointer aligned for the source type,
287        // which may not be aligned for the destination type.
288        let empty: Vec<u8> = Vec::new();
289        assert_eq!(cast_slice::<u8, i32>(&empty), Some([].as_slice()));
290
291        let mut empty: Vec<u8> = Vec::new();
292        assert_eq!(
293            cast_mut_slice::<u8, i32>(&mut empty),
294            Some([].as_mut_slice())
295        );
296
297        let mut empty: Vec<MaybeUninit<u8>> = Vec::new();
298        assert!(cast_uninit_mut_slice::<u8, i32>(&mut empty).is_some_and(|s| s.is_empty()));
299
300        let empty: Vec<u8> = Vec::new();
301        assert_eq!(cast_vec::<u8, i32>(empty), Some(Vec::new()));
302    }
303
304    #[test]
305    fn test_cast_vec() {
306        // Compatible types
307        let i32s = Vec::from([1, 2, 3]);
308        let (ptr, len, cap) = (i32s.as_ptr(), i32s.len(), i32s.capacity());
309        let f32s = cast_vec::<i32, f32>(i32s).unwrap();
310        assert_eq!(f32s.as_ptr(), ptr as *const f32);
311        assert_eq!(f32s.len(), len);
312        assert_eq!(f32s.capacity(), cap);
313
314        // Incompatible types
315        let i32s = Vec::from([1, 2, 3]);
316        let i8s = cast_vec::<i32, i8>(i32s);
317        assert!(i8s.is_none());
318    }
319
320    #[test]
321    fn test_cast_slice_fails_if_unaligned() {
322        let i8s = [1, 2, 3, 4, 5];
323        let i32s_a = cast_slice::<i8, i32>(&i8s);
324        let i32s_b = cast_slice::<i8, i32>(&i8s[1..]);
325
326        // At least one of `i32s_a` or `i32s_b`` will be incorrectly aligned for i32.
327        assert!(i32s_a.is_none() || i32s_b.is_none());
328    }
329
330    #[test]
331    fn test_cast_slice_fails_if_size_not_multiple_of_dst_size() {
332        let i8s = [1, 2, 3, 4, 5];
333        let i32s = cast_slice::<i8, i32>(&i8s);
334        assert!(i32s.is_none());
335    }
336
337    #[test]
338    fn test_cast_mut_slice() {
339        let mut i32s = [1, 2, 3];
340        let i32s_ptr = i32s.as_ptr();
341        let i8s = cast_mut_slice::<i32, i8>(&mut i32s).unwrap();
342        assert_eq!(i8s.as_ptr(), i32s_ptr as *const i8);
343        assert_eq!(i8s.len(), i32s.len() * 4);
344    }
345
346    #[test]
347    fn test_cast_uninit_mut_slice() {
348        let mut i32s = [1, 2, 3].map(MaybeUninit::new);
349        let i32s_ptr = i32s.as_ptr();
350        let i8s = cast_uninit_mut_slice::<i32, i8>(&mut i32s).unwrap();
351        assert_eq!(i8s.as_ptr(), i32s_ptr as *const MaybeUninit<i8>);
352        assert_eq!(i8s.len(), i32s.len() * 4);
353    }
354
355    #[test]
356    fn test_as_bytes_and_from_bytes() {
357        #[derive(Debug, PartialEq)]
358        struct SomeData {
359            field_a: [i32; 2],
360            field_b: [i32; 2],
361        }
362        // Safety: SomeData meets requirements for AsBytes, FromBytes.
363        unsafe impl AsBytes for SomeData {}
364        unsafe impl FromBytes for SomeData {}
365
366        let data = SomeData {
367            field_a: [1, 2],
368            field_b: [3, 4],
369        };
370        let bytes = data.as_bytes();
371
372        let recreated_data = SomeData::from_bytes(bytes);
373        assert_eq!(recreated_data, &data);
374    }
375}