proc_daemon/
coord.rs

1//! Lightweight coordination primitives with optional lock-free backend.
2//!
3//! When built with the `lockfree-coordination` feature, this module uses
4//! `crossbeam-channel` for MPMC lock-free channels. Otherwise it falls back
5//! to `std::sync::mpsc` unbounded channels.
6
7#[cfg(feature = "lockfree-coordination")]
8/// Channel facade backed by `crossbeam-channel` when the
9/// `lockfree-coordination` feature is enabled.
10pub mod chan {
11    pub use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
12
13    /// Non-blocking receive helper that mirrors the fallback API.
14    ///
15    /// Returns the next message if available or a `TryRecvError` if the
16    /// channel is empty or disconnected.
17    ///
18    /// # Errors
19    ///
20    /// Returns `Err(TryRecvError)` when the channel is empty or disconnected.
21    #[inline]
22    pub fn try_recv<T>(rx: &Receiver<T>) -> Result<T, TryRecvError> {
23        rx.try_recv()
24    }
25}
26
27#[cfg(not(feature = "lockfree-coordination"))]
28/// Channel facade backed by `std::sync::mpsc` when the
29/// `lockfree-coordination` feature is disabled.
30pub mod chan {
31    use std::sync::mpsc;
32
33    /// Type alias for `mpsc::Sender`.
34    pub type Sender<T> = mpsc::Sender<T>;
35
36    /// Type alias for `mpsc::Receiver`.
37    pub type Receiver<T> = mpsc::Receiver<T>;
38
39    /// Error type for non-blocking receive operations.
40    #[derive(Debug)]
41    pub enum TryRecvError {
42        /// The channel is empty.
43        Empty,
44        /// The channel is disconnected.
45        Disconnected,
46    }
47
48    /// Create an unbounded channel returning `(Sender, Receiver)`.
49    #[must_use]
50    pub fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
51        mpsc::channel()
52    }
53
54    /// Non-blocking receive helper that mirrors the crossbeam API.
55    ///
56    /// Returns the next message if available or a `TryRecvError` if the
57    /// channel is empty or disconnected.
58    ///
59    /// # Errors
60    ///
61    /// Returns `Err(TryRecvError)` when the channel is empty or disconnected.
62    #[inline]
63    pub fn try_recv<T>(rx: &Receiver<T>) -> Result<T, TryRecvError> {
64        rx.try_recv().map_err(|e| match e {
65            mpsc::TryRecvError::Empty => TryRecvError::Empty,
66            mpsc::TryRecvError::Disconnected => TryRecvError::Disconnected,
67        })
68    }
69}