interprocess 2.4.0

Interprocess communication toolkit
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#![allow(dead_code)]

#[cfg(unix)]
use std::os::unix::io::RawFd;
use std::{
    io,
    mem::{size_of, ManuallyDrop, MaybeUninit},
    num::{NonZeroU8, Saturating},
    ops::ControlFlow,
    pin::Pin,
    slice,
    sync::PoisonError,
    task::{RawWaker, RawWakerVTable, Waker},
    time::{Duration, Instant},
};
#[cfg(windows)]
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};

/// Utility trait that, if used as a supertrait, prevents other crates from implementing the
/// trait.
pub(crate) trait Sealed {}
pub(crate) trait DebugExpectExt: Sized {
    fn debug_expect(self, msg: &str);
}

pub(crate) static LOCK_POISON: &str = "unexpected lock poison";
pub(crate) fn poison_error<T>(_: PoisonError<T>) -> io::Error { io::Error::other(LOCK_POISON) }

pub(crate) trait OrErrno<T>: Sized {
    fn true_or_errno(self, f: impl FnOnce() -> T) -> io::Result<T>;
    #[inline(always)]
    fn true_val_or_errno(self, value: T) -> io::Result<T> { self.true_or_errno(|| value) }
    fn false_or_errno(self, f: impl FnOnce() -> T) -> io::Result<T>;
    #[inline(always)]
    fn false_val_or_errno(self, value: T) -> io::Result<T> { self.true_or_errno(|| value) }
}
impl<B: ToBool, T> OrErrno<T> for B {
    #[inline]
    fn true_or_errno(self, f: impl FnOnce() -> T) -> io::Result<T> {
        if self.to_bool() {
            Ok(f())
        } else {
            Err(io::Error::last_os_error())
        }
    }
    fn false_or_errno(self, f: impl FnOnce() -> T) -> io::Result<T> {
        if !self.to_bool() {
            Ok(f())
        } else {
            Err(io::Error::last_os_error())
        }
    }
}

#[cfg(unix)]
pub(crate) trait FdOrErrno: Sized {
    fn fd_or_errno(self) -> io::Result<Self>;
}
#[cfg(unix)]
impl FdOrErrno for RawFd {
    #[inline]
    fn fd_or_errno(self) -> io::Result<Self> { (self != -1).true_val_or_errno(self) }
}

#[cfg(windows)]
pub(crate) trait HandleOrErrno: Sized {
    fn handle_or_errno(self) -> io::Result<Self>;
}
#[cfg(windows)]
impl HandleOrErrno for HANDLE {
    #[inline]
    fn handle_or_errno(self) -> io::Result<Self> {
        (self != INVALID_HANDLE_VALUE).true_val_or_errno(self)
    }
}

// FUTURE remove
pub(crate) trait ControlFlowExt {
    type B;
    type C;
    // "pf" means "polyfill"
    fn break_value_pf(self) -> Option<Self::B>;
    fn continue_value_pf(self) -> Option<Self::C>;
    fn is_break_pf(&self) -> bool;
    fn is_continue_pf(&self) -> bool;
}
impl<B, C> ControlFlowExt for ControlFlow<B, C> {
    type B = B;
    type C = C;
    #[inline(always)]
    fn break_value_pf(self) -> Option<B> {
        match self {
            Self::Break(v) => Some(v),
            Self::Continue(_) => None,
        }
    }
    #[inline(always)]
    fn continue_value_pf(self) -> Option<C> {
        match self {
            Self::Break(_) => None,
            Self::Continue(v) => Some(v),
        }
    }
    #[inline(always)]
    fn is_break_pf(&self) -> bool { matches!(self, Self::Break(..)) }
    #[inline(always)]
    fn is_continue_pf(&self) -> bool { matches!(self, Self::Continue(..)) }
}

pub(crate) trait OptionExt {
    type Value;
    fn break_some(self) -> ControlFlow<Self::Value>;
}
impl<T> OptionExt for Option<T> {
    type Value = T;
    fn break_some(self) -> ControlFlow<T> {
        match self {
            Some(v) => ControlFlow::Break(v),
            None => ControlFlow::Continue(()),
        }
    }
}

pub(crate) trait OptionTimeoutExt {
    type Output;
    fn some_or_timeout(self) -> io::Result<Self::Output>;
}
impl<O> OptionTimeoutExt for Option<io::Result<O>> {
    type Output = O;
    #[inline(always)]
    fn some_or_timeout(self) -> io::Result<O> {
        match self {
            Some(r) => r,
            None => Err(io::Error::from(io::ErrorKind::TimedOut)),
        }
    }
}

pub(crate) trait ToBool {
    fn to_bool(self) -> bool;
}
impl ToBool for bool {
    #[inline(always)]
    fn to_bool(self) -> bool { self }
}
impl ToBool for i32 {
    #[inline(always)]
    fn to_bool(self) -> bool { self != 0 }
}

pub(crate) trait BoolExt {
    fn to_i32(self) -> i32;
    fn to_usize(self) -> usize;
}
impl BoolExt for bool {
    #[inline(always)] #[rustfmt::skip] // oh come on now
    fn to_i32(self) -> i32 {
        if self { 1 } else { 0 }
    }
    #[inline(always)] #[rustfmt::skip]
    fn to_usize(self) -> usize {
        if self { 1 } else { 0 }
    }
}

// FUTURE replace with std::ptr::from_{ref,mut}
#[inline(always)]
pub(crate) const fn ref2ptr<T: ?Sized>(r: &T) -> *const T { r }
#[inline(always)]
pub(crate) fn mut2ptr<T: ?Sized>(r: &mut T) -> *mut T { r }

impl<T, E: std::fmt::Debug> DebugExpectExt for Result<T, E> {
    #[inline]
    #[track_caller]
    fn debug_expect(self, msg: &str) {
        if cfg!(debug_assertions) {
            self.expect(msg);
        }
    }
}
impl<T> DebugExpectExt for Option<T> {
    #[inline]
    #[track_caller]
    fn debug_expect(self, msg: &str) {
        if cfg!(debug_assertions) {
            self.expect(msg);
        }
    }
}

pub(crate) trait NumExt: Sized {
    #[inline]
    fn saturate(self) -> Saturating<Self> { Saturating(self) }
}
impl<T> NumExt for T {}

pub(crate) trait SubUsizeExt: TryInto<usize> + Sized {
    fn to_usize(self) -> usize;
}
pub(crate) trait SubIsizeExt: TryInto<usize> + Sized {
    fn to_isize(self) -> isize;
}
macro_rules! impl_subsize {
    ($src:ident to usize) => {
        impl SubUsizeExt for $src {
            #[inline(always)]
            fn to_usize(self) -> usize {
                self as usize
            }
        }
    };
    ($src:ident to isize) => {
        impl SubIsizeExt for $src {
            #[inline(always)]
            // we don't run on 16-bit platforms
            #[allow(clippy::cast_possible_wrap)]
            fn to_isize(self) -> isize {
                self as isize
            }
        }
    };
    ($($src:ident to $dst:ident)+) => {$(
        impl_subsize!($src to $dst);
    )+};
}
// See platform_check.rs.
impl_subsize! {
    u8  to usize
    u16 to usize
    u32 to usize
    i8  to isize
    i16 to isize
    i32 to isize
    u8  to isize
    u16 to isize
}

// TODO find a more elegant way
pub(crate) trait RawOsErrorExt {
    fn eeq(self, other: u32) -> bool;
}
impl RawOsErrorExt for Option<i32> {
    #[inline(always)]
    #[allow(clippy::cast_sign_loss)] // bitwise comparison
    fn eeq(self, other: u32) -> bool {
        match self {
            Some(n) => n as u32 == other,
            None => false,
        }
    }
}

/// Crudely casts a slice without any checks, blindly presuming that the size of `T` is equal to
/// that of `U`.
pub(crate) const unsafe fn cast_slice<T, U>(s: &[T]) -> &[U] {
    // FUTURE use const assertion
    if size_of::<T>() != size_of::<U>() {
        panic!("element sizes must be equal");
    }
    unsafe { slice::from_raw_parts(s.as_ptr().cast(), s.len()) }
}
/// Mutable version of [`cast_slice`].
pub(crate) unsafe fn cast_slice_mut<T, U>(s: &mut [T]) -> &mut [U] {
    // FUTURE use const assertion
    if size_of::<T>() != size_of::<U>() {
        panic!("element sizes must be equal");
    }
    unsafe { slice::from_raw_parts_mut(s.as_mut_ptr().cast(), s.len()) }
}

#[inline(always)]
// SAFETY: weaker refinement
pub(crate) fn weaken_buf_init<T>(s: &[T]) -> &[MaybeUninit<T>] { unsafe { cast_slice(s) } }

#[inline(always)]
pub(crate) unsafe fn assume_slice_init<T>(s: &[MaybeUninit<T>]) -> &[T] {
    // SAFETY: same slice, stronger refinement
    unsafe { cast_slice(s) }
}
#[inline(always)]
pub(crate) unsafe fn assume_slice_init_mut<T>(s: &mut [MaybeUninit<T>]) -> &mut [T] {
    // SAFETY: as above
    unsafe { cast_slice_mut(s) }
}

#[inline(always)]
pub(crate) fn contains_nuls(s: &[u8]) -> bool {
    #[cfg(unix)]
    {
        unsafe { libc::strnlen(s.as_ptr().cast(), s.len()) != s.len() }
    }
    #[cfg(not(unix))]
    {
        s.contains(&0)
    }
}
#[inline(always)]
pub(crate) const unsafe fn assume_nonzero_slice(s: &[u8]) -> &[NonZeroU8] {
    unsafe { cast_slice(s) }
}
#[inline(always)]
pub(crate) unsafe fn assume_nonzero_slice_mut(s: &mut [u8]) -> &mut [NonZeroU8] {
    unsafe { cast_slice_mut(s) }
}
#[inline(always)]
pub(crate) fn check_nonzero_slice(s: &[u8]) -> Option<&[NonZeroU8]> {
    let false = contains_nuls(s) else { return None };
    // SAFETY: we've just checked for nul bytes
    Some(unsafe { assume_nonzero_slice(s) })
}
#[inline(always)]
pub(crate) fn check_nonzero_slice_mut(s: &mut [u8]) -> Option<&mut [NonZeroU8]> {
    let false = contains_nuls(s) else { return None };
    // SAFETY: as above
    Some(unsafe { cast_slice_mut(s) })
}
// SAFETY: weaker refinement
#[inline(always)]
pub(crate) fn weaken_nonzero_slice(s: &[NonZeroU8]) -> &[u8] { unsafe { cast_slice(s) } }

pub(crate) trait UnpinExt: Unpin {
    #[inline]
    fn pin(&mut self) -> Pin<&mut Self> { Pin::new(self) }
}
impl<T: Unpin + ?Sized> UnpinExt for T {}

/// Generalizes over `&mut [u8]` and `&mut [MaybeUninit<u8>]`.
///
/// # Safety
/// The pointer returned by `as_ptr` must be valid for writes of length returned by a preceding
/// call to `len` for at least as long as no methods other than those that are in this trait are
/// called.
pub(crate) unsafe trait AsBuf {
    fn as_ptr(&mut self) -> *mut u8;
    fn len(&mut self) -> usize;
}
unsafe impl AsBuf for [u8] {
    #[inline(always)]
    fn as_ptr(&mut self) -> *mut u8 { self.as_mut_ptr() }
    #[inline(always)]
    fn len(&mut self) -> usize { <[u8]>::len(self) }
}
unsafe impl AsBuf for [MaybeUninit<u8>] {
    #[inline(always)]
    fn as_ptr(&mut self) -> *mut u8 { self.as_mut_ptr().cast() }
    #[inline(always)]
    fn len(&mut self) -> usize { <[MaybeUninit<u8>]>::len(self) }
}

pub(crate) fn spin_with_timeout<S, R>(
    state: &mut S,
    timeout: Option<Duration>,
    start: impl FnOnce(&mut S) -> ControlFlow<io::Result<R>>,
    spin: impl FnMut(&mut S, Option<Duration>) -> ControlFlow<io::Result<R>>,
    update_timeout: impl FnMut(&mut S, Duration),
) -> Option<io::Result<R>> {
    if let ControlFlow::Break(val) = start(state) {
        Some(val)
    } else {
        spin_with_timeout_loop(state, timeout, spin, update_timeout)
    }
}
#[cold]
fn spin_with_timeout_loop<S, R>(
    state: &mut S,
    mut timeout: Option<Duration>,
    mut spin: impl FnMut(&mut S, Option<Duration>) -> ControlFlow<io::Result<R>>,
    mut update_timeout: impl FnMut(&mut S, Duration),
) -> Option<io::Result<R>> {
    let end = match timeout.map(timeout_expiry).transpose() {
        Ok(end_or_none) => end_or_none,
        Err(e) => return Some(Err(e)),
    };

    loop {
        if let ControlFlow::Break(val) = spin(state, timeout) {
            break Some(val);
        }
        if let Some(end) = end {
            let cur = Instant::now();
            if cur >= end {
                update_timeout(state, Duration::ZERO);
                break None;
            }
            let remain = end.saturating_duration_since(cur);
            timeout = Some(remain);
            update_timeout(state, remain);
        }
    }
}

// FUTURE remove in favor of Waker::noop
#[inline(always)]
pub(crate) fn noop_waker() -> ManuallyDrop<Waker> {
    ManuallyDrop::new(unsafe { Waker::from_raw(noop_raw_waker()) })
}
#[inline(always)]
fn noop_raw_waker() -> RawWaker {
    static VTAB: RawWakerVTable = RawWakerVTable::new(|_| noop_raw_waker(), drop, drop, drop);
    RawWaker::new(std::ptr::null(), &VTAB)
}

pub(crate) fn timeout_expiry(timeout: Duration) -> io::Result<Instant> {
    let msg = "timeout expiry time overflowed std::time::Instant";
    Instant::now()
        .checked_add(timeout)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, msg))
}

pub(crate) struct CannotUnwind(());
impl CannotUnwind {
    pub fn begin() -> Self { Self(()) }
    pub fn end(self) { std::mem::forget(self) }
}
impl Drop for CannotUnwind {
    fn drop(&mut self) { std::process::abort(); }
}