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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use crate::*;
use std::{
    marker::PhantomData,
    mem,
    mem::{ManuallyDrop, MaybeUninit},
    ops::Deref,
    slice,
};

/// Marker trait for Pod types
///
/// This is not a general Pod type and only supposed to be used for interaction with this
/// crate.
///
/// See also the crate documentation.
///
/// # Safety
///
/// For all sized types `T: Pod`, transmuting any array of type `[u8; size_of::<T>()]` to
/// `T` must produce a valid value.
///
/// For all types `T: Pod`, overwriting the contents of `t: &mut T` with any array of type
/// `[u8; size_of_val(t)]` must produce a valid value.
pub unsafe trait Pod {}

/// Returns an instance of `T` whose object representation is `0` in all non-padding bytes
pub fn pod_zeroed<T: Pod>() -> T {
    unsafe { mem::zeroed() }
}

/// Converts `u` to `T`
///
/// `u` and `T` must have the same size.
pub fn pod_read<T: Pod, U: Packed + ?Sized>(u: &U) -> Result<T> {
    let mut t = pod_zeroed();
    pod_write(u, &mut t)?;
    Ok(t)
}

/// Converts `u` into an iterator of `T`
///
/// The size of `u` must be a multiple of the size of `T`
pub fn pod_iter<'a, T: Pod + 'a, U: Packed + ?Sized>(
    u: &'a U,
) -> Result<impl Iterator<Item = T> + 'a> {
    if mem::size_of::<T>() != 0 && mem::size_of_val(u) % mem::size_of::<T>() != 0 {
        einval()
    } else {
        Ok(Iter {
            buf: as_bytes(u),
            _pd: PhantomData,
        })
    }
}

struct Iter<'a, T> {
    buf: &'a [u8],
    _pd: PhantomData<fn() -> T>,
}

impl<'a, T: Pod> Iterator for Iter<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.buf.is_empty() {
            None
        } else {
            let t = pod_read_init(self.buf).unwrap();
            self.buf = &self.buf[mem::size_of::<T>()..];
            Some(t)
        }
    }
}

/// Converts an initial port of `u` to `T`
///
/// The size of `u` must be equal to or larger than the size of `T`.
pub fn pod_read_init<T: Pod, U: Packed + ?Sized>(u: &U) -> Result<T> {
    let mut t = pod_zeroed();
    pod_write_common_prefix(u, &mut t)?;
    Ok(t)
}

/// Writes `u` to `t`
///
/// `u` and `t` must have the same size.
pub fn pod_write<T: Pod + ?Sized, U: Packed + ?Sized>(u: &U, t: &mut T) -> Result<()> {
    if mem::size_of_val(t) != mem::size_of_val(u) {
        einval()
    } else {
        pod_write_common_prefix(u, t)
    }
}

/// Writes an initial portion of `u` to `t`
///
/// The size of `u` must be equal to or larger than the size of `t`.
fn pod_write_common_prefix<T: Pod + ?Sized, U: Packed + ?Sized>(
    u: &U,
    t: &mut T,
) -> Result<()> {
    if mem::size_of_val(t) > mem::size_of_val(u) {
        einval()
    } else {
        unsafe {
            let dst = t as *mut _ as *mut u8;
            let src = u as *const _ as *const u8;
            std::ptr::copy_nonoverlapping(src, dst, mem::size_of_val(t));
        }
        Ok(())
    }
}

unsafe impl<T: Pod> Pod for [T] {
}

// TODO: https://github.com/rust-lang/rust/pull/79135
// unsafe impl<T: Pod, const N: usize> Pod for [T; N] {
// }

unsafe impl<T> Pod for *const T {
}

unsafe impl<T> Pod for *mut T {
}

unsafe impl<T> Pod for MaybeUninit<T> {
}

macro_rules! imp_pod {
    ($($path:path)*) => {
        $(unsafe impl Pod for $path {})*
    }
}

imp_pod! {
    u8
    u16
    u32
    u64
    u128
    usize
    i8
    i16
    i32
    i64
    i128
    isize

    c::sockaddr
    c::sockaddr_storage
    c::sockaddr_un
    c::sockaddr_in
    c::sockaddr_in6

    c::msghdr
    c::cmsghdr

    c::in6_pktinfo

    c::siginfo_t
    c::flock
    c::timespec
    c::timeval
    c::linger

    OwnedFd
    Fd
}

#[cfg(not(any(target_os = "macos", target_os = "openbsd")))]
imp_pod! {
    c::sigset_t
}

#[cfg(target_os = "linux")]
imp_pod! {
    c::sockaddr_alg
    c::sockaddr_nl
    c::sockaddr_ll
    c::sockaddr_vm
    c::signalfd_siginfo
    c::nlmsghdr
    c::nlattr
    c::ifinfomsg
    c::input_event
    c::open_how
    c::sched_attr
    c::sched_param
}

#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd")))]
imp_pod! {
    c::ucred
    c::in_pktinfo
    c::ip_mreq
    c::ip_mreqn
}

/// Marker trait for types without padding
///
/// # Safety
///
/// Types that implement this must not have padding bytes
pub unsafe trait Packed {}

unsafe impl<T: Packed> Packed for [T] {
}

// TODO: https://github.com/rust-lang/rust/pull/79135
// unsafe impl<T: Packed, const N: usize> Packed for [T; N] {
// }

unsafe impl<T> Packed for *const T {
}

unsafe impl<T> Packed for *mut T {
}

macro_rules! imp_packed {
    ($($path:path)*) => {
        $(unsafe impl Packed for $path {})*
    }
}

imp_packed! {
    u8
    u16
    u32
    u64
    u128
    usize
    i8
    i16
    i32
    i64
    i128
    isize

    OwnedFd
    Fd
}

/// Returns the object representation of `t`
pub fn as_bytes<T: Packed + ?Sized>(t: &T) -> &[u8] {
    unsafe {
        let ptr = t as *const _ as *const u8;
        slice::from_raw_parts(ptr, mem::size_of_val(t))
    }
}

/// Returns the mutable object representation of `t`
pub fn as_bytes_mut<T: Pod + Packed + ?Sized>(t: &mut T) -> &mut [u8] {
    unsafe {
        let ptr = t as *mut _ as *mut u8;
        slice::from_raw_parts_mut(ptr, mem::size_of_val(t))
    }
}

/// Transparent wrapper that asserts that a type is `Pod`
#[repr(transparent)]
#[derive(Copy)]
pub struct AssertPod<T: ?Sized>(ManuallyDrop<T>);

impl<T: ?Sized> AssertPod<T> {
    /// Wraps a `&mut T`
    ///
    /// # Safety
    ///
    /// `T` must follow the `Pod` contract.
    pub unsafe fn new(t: &mut T) -> &mut Self {
        &mut *(t as *mut T as *mut AssertPod<T>)
    }
}

impl<T: Copy> Clone for AssertPod<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> AssertPod<T> {
    /// Unwraps the contained object
    ///
    /// # Safety
    ///
    /// `T` must follow the `Pod` contract.
    pub unsafe fn unwrap(self) -> T {
        ManuallyDrop::into_inner(self.0)
    }
}

unsafe impl<T: ?Sized> Pod for AssertPod<T> {
}

/// Transparent wrapper that asserts that a type is `Packed`
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct AssertPacked<T: ?Sized>(T);

impl<T: ?Sized> AssertPacked<T> {
    /// Wraps a `&T`
    ///
    /// # Safety
    ///
    /// `T` must follow the `Packed` contract.
    pub unsafe fn new(t: &T) -> &Self {
        &*(t as *const T as *const AssertPacked<T>)
    }
}

unsafe impl<T: ?Sized> Packed for AssertPacked<T> {
}

impl<T: ?Sized> Deref for AssertPacked<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Asserts that `T` is `Pod`
///
/// # Safety
///
/// `T` must follow the `Pod` contract.
pub unsafe fn assert_pod<T: ?Sized>(t: &mut T) -> &mut AssertPod<T> {
    AssertPod::new(t)
}

/// Asserts that `T` is `Packed`
///
/// # Safety
///
/// `T` must follow the `Packed` contract.
pub unsafe fn assert_packed<T: ?Sized>(t: &T) -> &AssertPacked<T> {
    AssertPacked::new(t)
}