reovim-kernel 0.14.3

Core kernel mechanisms for reovim (Linux kernel/ equivalent)
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Channel abstractions for inter-subsystem communication.
//!
//! This module provides thin wrappers around `std::sync::mpsc` channels,
//! keeping the kernel runtime-agnostic (no tokio dependency).
//!
//! # Design Philosophy
//!
//! Following the "mechanisms not policy" principle:
//! - Provides basic channel primitives
//! - No opinion on how they should be used
//! - Runtime integration is left to higher layers
//!
//! # Channel Types
//!
//! - **Unbounded MPSC**: Multiple producers, single consumer, unlimited buffer
//! - **Bounded MPSC**: Multiple producers, single consumer, fixed capacity
//! - **Oneshot**: Single-use channel for request-response patterns
//!
//! # Example
//!
//! ```
//! use reovim_kernel::api::v1::*;
//!
//! // Unbounded channel
//! let (tx, rx) = channel::<i32>();
//! tx.send(42).unwrap();
//! assert_eq!(rx.recv().unwrap(), 42);
//!
//! // Bounded channel with capacity 2
//! let (tx, rx) = bounded::<i32>(2);
//! tx.send(1).unwrap();
//! tx.send(2).unwrap();
//! // tx.send(3) would block until space is available
//!
//! // Oneshot for request-response
//! let (tx, rx) = oneshot::<String>();
//! tx.send("response".to_string()).unwrap();
//! assert_eq!(rx.recv().unwrap(), "response");
//! ```

use std::{sync::mpsc, time::Duration};

use reovim_arch::sync::Mutex;

// ============================================================================
// Unbounded Channel
// ============================================================================

/// Sender for unbounded MPSC channel.
///
/// Cloning creates a new sender to the same channel.
pub struct Sender<T>(mpsc::Sender<T>);

// Manual Clone impl because mpsc::Sender<T> is Clone without requiring T: Clone
impl<T> Clone for Sender<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// Receiver for unbounded MPSC channel.
///
/// Only one receiver exists per channel.
pub struct Receiver<T>(mpsc::Receiver<T>);

/// Error returned when sending fails because the receiver was dropped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendError<T>(pub T);

impl<T> std::fmt::Display for SendError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "sending on a closed channel")
    }
}

impl<T: std::fmt::Debug> std::error::Error for SendError<T> {}

/// Error returned when receiving fails because the channel is empty and closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecvError;

impl std::fmt::Display for RecvError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "receiving on a closed channel")
    }
}

impl std::error::Error for RecvError {}

/// Error returned when `try_recv` fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TryRecvError {
    /// No message available.
    Empty,
    /// Channel is closed.
    Disconnected,
}

impl std::fmt::Display for TryRecvError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => write!(f, "channel is empty"),
            Self::Disconnected => write!(f, "channel is disconnected"),
        }
    }
}

impl std::error::Error for TryRecvError {}

impl<T> Sender<T> {
    /// Send a value through the channel.
    ///
    /// # Errors
    ///
    /// Returns `Err(SendError(value))` if the receiver has been dropped.
    pub fn send(&self, value: T) -> Result<(), SendError<T>> {
        self.0.send(value).map_err(|e| SendError(e.0))
    }
}

impl<T> std::fmt::Debug for Sender<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sender").finish_non_exhaustive()
    }
}

impl<T> Receiver<T> {
    /// Block until a value is received.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` if the channel is closed.
    pub fn recv(&self) -> Result<T, RecvError> {
        self.0.recv().map_err(|_| RecvError)
    }

    /// Try to receive without blocking.
    ///
    /// # Errors
    ///
    /// Returns `Err(TryRecvError::Empty)` if no message is available,
    /// or `Err(TryRecvError::Disconnected)` if the channel is closed.
    pub fn try_recv(&self) -> Result<T, TryRecvError> {
        self.0.try_recv().map_err(|e| match e {
            mpsc::TryRecvError::Empty => TryRecvError::Empty,
            mpsc::TryRecvError::Disconnected => TryRecvError::Disconnected,
        })
    }

    /// Block until a value is received or timeout expires.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` on timeout or if channel is closed.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvError> {
        self.0.recv_timeout(timeout).map_err(|_| RecvError)
    }

    /// Create an iterator over received values.
    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
        self.0.iter()
    }

    /// Try to receive all available values without blocking.
    pub fn try_iter(&self) -> impl Iterator<Item = T> + '_ {
        self.0.try_iter()
    }
}

impl<T> std::fmt::Debug for Receiver<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Receiver").finish_non_exhaustive()
    }
}

/// Create an unbounded MPSC channel.
///
/// # Example
///
/// ```
/// use reovim_kernel::api::v1::*;
///
/// let (tx, rx) = channel::<i32>();
/// tx.send(42).unwrap();
/// assert_eq!(rx.recv().unwrap(), 42);
/// ```
#[must_use]
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
    let (tx, rx) = mpsc::channel();
    (Sender(tx), Receiver(rx))
}

// ============================================================================
// Bounded Channel
// ============================================================================

/// Sender for bounded MPSC channel.
pub struct BoundedSender<T>(mpsc::SyncSender<T>);

// Manual Clone impl because mpsc::SyncSender<T> is Clone without requiring T: Clone
impl<T> Clone for BoundedSender<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// Receiver for bounded MPSC channel (same as unbounded).
pub struct BoundedReceiver<T>(mpsc::Receiver<T>);

/// Error returned when `try_send` fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrySendError<T> {
    /// Channel is full.
    Full(T),
    /// Channel is closed.
    Disconnected(T),
}

impl<T> std::fmt::Display for TrySendError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Full(_) => write!(f, "channel is full"),
            Self::Disconnected(_) => write!(f, "channel is disconnected"),
        }
    }
}

impl<T: std::fmt::Debug> std::error::Error for TrySendError<T> {}

impl<T> BoundedSender<T> {
    /// Send a value, blocking if the channel is full.
    ///
    /// # Errors
    ///
    /// Returns `Err(SendError(value))` if the receiver has been dropped.
    pub fn send(&self, value: T) -> Result<(), SendError<T>> {
        self.0.send(value).map_err(|e| SendError(e.0))
    }

    /// Try to send without blocking.
    ///
    /// # Errors
    ///
    /// Returns `Err(TrySendError::Full(value))` if the channel is full,
    /// or `Err(TrySendError::Disconnected(value))` if the receiver was dropped.
    pub fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
        self.0.try_send(value).map_err(|e| match e {
            mpsc::TrySendError::Full(v) => TrySendError::Full(v),
            mpsc::TrySendError::Disconnected(v) => TrySendError::Disconnected(v),
        })
    }
}

impl<T> std::fmt::Debug for BoundedSender<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoundedSender").finish_non_exhaustive()
    }
}

impl<T> BoundedReceiver<T> {
    /// Block until a value is received.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` if the channel is closed.
    pub fn recv(&self) -> Result<T, RecvError> {
        self.0.recv().map_err(|_| RecvError)
    }

    /// Try to receive without blocking.
    ///
    /// # Errors
    ///
    /// Returns `Err(TryRecvError::Empty)` if no message is available,
    /// or `Err(TryRecvError::Disconnected)` if the channel is closed.
    #[cfg_attr(coverage_nightly, coverage(off))]
    pub fn try_recv(&self) -> Result<T, TryRecvError> {
        self.0.try_recv().map_err(|e| match e {
            mpsc::TryRecvError::Empty => TryRecvError::Empty,
            mpsc::TryRecvError::Disconnected => TryRecvError::Disconnected,
        })
    }

    /// Block until a value is received or timeout expires.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` on timeout or if the channel is closed.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvError> {
        self.0.recv_timeout(timeout).map_err(|_| RecvError)
    }

    /// Create an iterator over received values.
    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
        self.0.iter()
    }

    /// Try to receive all available values without blocking.
    pub fn try_iter(&self) -> impl Iterator<Item = T> + '_ {
        self.0.try_iter()
    }
}

impl<T> std::fmt::Debug for BoundedReceiver<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoundedReceiver").finish_non_exhaustive()
    }
}

/// Create a bounded MPSC channel with the specified capacity.
///
/// Senders will block when the channel is full.
///
/// # Example
///
/// ```
/// use reovim_kernel::api::v1::*;
///
/// let (tx, rx) = bounded::<i32>(2);
/// tx.send(1).unwrap();
/// tx.send(2).unwrap();
/// // tx.send(3) would block until space is available
///
/// assert_eq!(rx.recv().unwrap(), 1);
/// assert_eq!(rx.recv().unwrap(), 2);
/// ```
#[must_use]
pub fn bounded<T>(capacity: usize) -> (BoundedSender<T>, BoundedReceiver<T>) {
    let (tx, rx) = mpsc::sync_channel(capacity);
    (BoundedSender(tx), BoundedReceiver(rx))
}

// ============================================================================
// Oneshot Channel
// ============================================================================

/// Sender for oneshot channel.
///
/// Can only send a single value.
pub struct OneshotSender<T> {
    inner: Mutex<Option<mpsc::SyncSender<T>>>,
}

/// Receiver for oneshot channel.
///
/// Can only receive a single value.
pub struct OneshotReceiver<T>(mpsc::Receiver<T>);

impl<T> OneshotSender<T> {
    /// Send the value, consuming the sender.
    ///
    /// This can only be called once.
    ///
    /// # Errors
    ///
    /// Returns `Err(value)` if the receiver has been dropped.
    #[cfg_attr(coverage_nightly, coverage(off))]
    pub fn send(self, value: T) -> Result<(), T> {
        let sender = self.inner.lock().take();
        match sender {
            Some(tx) => tx.send(value).map_err(|e| e.0),
            None => Err(value),
        }
    }

    /// Check if the receiver is still waiting.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.inner.lock().is_some()
    }
}

impl<T> std::fmt::Debug for OneshotSender<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OneshotSender")
            .field("connected", &self.is_connected())
            .finish()
    }
}

impl<T> OneshotReceiver<T> {
    /// Block until the value is received.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` if the sender was dropped without sending.
    pub fn recv(self) -> Result<T, RecvError> {
        self.0.recv().map_err(|_| RecvError)
    }

    /// Try to receive without blocking.
    ///
    /// # Errors
    ///
    /// Returns `Err(TryRecvError::Empty)` if no value is available yet,
    /// or `Err(TryRecvError::Disconnected)` if the sender was dropped.
    pub fn try_recv(&self) -> Result<T, TryRecvError> {
        self.0.try_recv().map_err(|e| match e {
            mpsc::TryRecvError::Empty => TryRecvError::Empty,
            mpsc::TryRecvError::Disconnected => TryRecvError::Disconnected,
        })
    }

    /// Block until received or timeout expires.
    ///
    /// # Errors
    ///
    /// Returns `Err(RecvError)` on timeout or if the sender was dropped.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvError> {
        self.0.recv_timeout(timeout).map_err(|_| RecvError)
    }
}

impl<T> std::fmt::Debug for OneshotReceiver<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OneshotReceiver").finish_non_exhaustive()
    }
}

/// Create a oneshot channel for single-value communication.
///
/// Useful for request-response patterns where exactly one response is expected.
///
/// # Example
///
/// ```
/// use reovim_kernel::api::v1::*;
/// use std::thread;
///
/// let (tx, rx) = oneshot::<String>();
///
/// thread::spawn(move || {
///     tx.send("response".to_string()).unwrap();
/// });
///
/// assert_eq!(rx.recv().unwrap(), "response");
/// ```
#[must_use]
pub fn oneshot<T>() -> (OneshotSender<T>, OneshotReceiver<T>) {
    let (tx, rx) = mpsc::sync_channel(1);
    (
        OneshotSender {
            inner: Mutex::new(Some(tx)),
        },
        OneshotReceiver(rx),
    )
}