plain/
plain.rs

1use Error;
2
3/// A trait for plain data types that can be safely read from a byte slice.
4///
5/// A type can be [`Plain`](trait.Plain.html) if it is `#repr(C)` and only contains
6/// data with no possible invalid values. Types that _can't_ be `Plain`
7/// include, but are not limited to, `bool`, `char`, `enum`s, tuples,
8/// pointers and references.
9///
10/// At this moment, `Drop` types are also not legal, because
11/// compiler adds a special "drop flag" into the type. This is slated
12/// to change in the future.
13///
14/// On the other hand, arrays of a `Plain` type, and
15/// structures where all members are plain (and not `Drop`), are okay.
16///
17/// Structures that are not `#repr(C)`, while not necessarily illegal
18/// in principle, are largely useless because they don't have a stable
19/// layout. For example, the compiler is allowed to reorder fields
20/// arbitrarily.
21///
22/// All methods of this trait are implemented automatically as wrappers
23/// for crate-level funtions.
24///
25pub unsafe trait Plain {
26    #[inline(always)]
27    fn from_bytes(bytes: &[u8]) -> Result<&Self, Error>
28    where
29        Self: Sized,
30    {
31        ::from_bytes(bytes)
32    }
33
34    #[inline(always)]
35    fn slice_from_bytes(bytes: &[u8]) -> Result<&[Self], Error>
36    where
37        Self: Sized,
38    {
39        ::slice_from_bytes(bytes)
40    }
41
42    #[inline(always)]
43    fn slice_from_bytes_len(bytes: &[u8], len: usize) -> Result<&[Self], Error>
44    where
45        Self: Sized,
46    {
47        ::slice_from_bytes_len(bytes, len)
48    }
49
50    #[inline(always)]
51    fn from_mut_bytes(bytes: &mut [u8]) -> Result<&mut Self, Error>
52    where
53        Self: Sized,
54    {
55        ::from_mut_bytes(bytes)
56    }
57
58    #[inline(always)]
59    fn slice_from_mut_bytes(bytes: &mut [u8]) -> Result<&mut [Self], Error>
60    where
61        Self: Sized,
62    {
63        ::slice_from_mut_bytes(bytes)
64    }
65
66    #[inline(always)]
67    fn slice_from_mut_bytes_len(bytes: &mut [u8], len: usize) -> Result<&mut [Self], Error>
68    where
69        Self: Sized,
70    {
71        ::slice_from_mut_bytes_len(bytes, len)
72    }
73
74    #[inline(always)]
75    fn copy_from_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
76        ::copy_from_bytes(self, bytes)
77    }
78}
79
80unsafe impl Plain for u8 {}
81unsafe impl Plain for u16 {}
82unsafe impl Plain for u32 {}
83unsafe impl Plain for u64 {}
84unsafe impl Plain for usize {}
85
86unsafe impl Plain for i8 {}
87unsafe impl Plain for i16 {}
88unsafe impl Plain for i32 {}
89unsafe impl Plain for i64 {}
90unsafe impl Plain for isize {}
91
92unsafe impl<S> Plain for [S]
93where
94    S: Plain,
95{
96}