imping_runtime/plain.rs
1//! Plain data: types for which every bit pattern is a valid value.
2
3use crate::strings::{CStrBuf, CStrPtr, WStrBuf, WStrPtr};
4
5/// A type for which every bit pattern of its size is a valid value, so it can
6/// be read from and written to the target's memory without checks.
7///
8/// Implemented for integers, floats, raw pointers to sized types, the string
9/// types and arrays of plain types; generated bindings add enum newtypes and
10/// all-plain structs and unions. `bool`, function pointers and references
11/// have invalid bit patterns, so they aren't plain.
12///
13/// # Safety
14///
15/// Every bit pattern of `size_of::<Self>()` bytes must be a valid value of
16/// `Self`.
17pub unsafe trait Plain: Copy + 'static {}
18
19macro_rules! plain {
20 ($($ty:ty),*) => {
21 $(
22 // SAFETY: Every bit pattern is a valid value of a primitive
23 // integer or float.
24 unsafe impl Plain for $ty {}
25 )*
26 };
27}
28
29plain!(
30 u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
31);
32
33// SAFETY: any address is a valid raw pointer, dereferenceable or not.
34unsafe impl<T: 'static> Plain for *const T {}
35
36// SAFETY: As for `*const T`.
37unsafe impl<T: 'static> Plain for *mut T {}
38
39// SAFETY: An array has no padding between elements, and every bit pattern of
40// each element is valid.
41unsafe impl<T: Plain, const N: usize> Plain for [T; N] {}
42
43// SAFETY: A transparent wrapper of a raw pointer.
44unsafe impl Plain for CStrPtr {}
45
46// SAFETY: A transparent wrapper of a raw pointer.
47unsafe impl Plain for WStrPtr {}
48
49// SAFETY: A transparent wrapper of a byte array.
50unsafe impl<const N: usize> Plain for CStrBuf<N> {}
51
52// SAFETY: A transparent wrapper of a `u16` array.
53unsafe impl<const N: usize> Plain for WStrBuf<N> {}