rtsc 0.4.5

Real-time Synchronization Components
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use std::{marker::PhantomData, sync::Arc, time::Duration};

use crate::condvar_api::RawCondvar;
use crate::locking::{Condvar, RawMutex};
use crate::{data_policy::StorageTryPushOutput, Error, Result};
use lock_api::RawMutex as RawMutexTrait;
use object_id::UniqueId;

/// Channel storage trait
pub trait ChannelStorage<T: Sized> {
    /// Creates a new storage with the specified capacity and ordering
    fn with_capacity_and_ordering(capacity: usize, ordering: bool) -> Self
    where
        Self: Sized;
    /// Tries to push a value into the storage
    fn try_push(&mut self, value: T) -> StorageTryPushOutput<T>;
    /// Gets a value from the storage
    fn get(&mut self) -> Option<T>;
    /// Returns the length of the storage
    fn len(&self) -> usize;
    /// Returns true if the storage is full
    fn is_full(&self) -> bool;
    /// Returns true if the storage is empty
    fn is_empty(&self) -> bool;
}

/// An abstract trait for data channels and hubs
pub trait DataChannel<T: Sized> {
    /// Sends a value to the channel
    fn send(&self, value: T) -> Result<()>;
    /// Tries to send a value to the channel (non-blocking)
    fn try_send(&self, value: T) -> Result<()>;
    /// Receives a value from the channel
    fn recv(&self) -> Result<T>;
    /// Tries to receive a value from the channel (non-blocking)
    fn try_recv(&self) -> Result<T>;
    /// Returns true if the channel is alive
    fn is_alive(&self) -> bool {
        true
    }
}

impl<T, S, M, CV> DataChannel<T> for BaseSender<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    fn send(&self, value: T) -> Result<()> {
        self.send(value)
    }
    fn try_send(&self, value: T) -> Result<()> {
        self.try_send(value)
    }
    fn try_recv(&self) -> Result<T> {
        Err(Error::Unimplemented)
    }
    fn recv(&self) -> Result<T> {
        Err(Error::Unimplemented)
    }
    fn is_alive(&self) -> bool {
        self.is_alive()
    }
}

impl<T, S, M, CV> DataChannel<T> for BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    fn send(&self, _value: T) -> Result<()> {
        Err(Error::Unimplemented)
    }
    fn try_send(&self, _value: T) -> Result<()> {
        Err(Error::Unimplemented)
    }
    fn try_recv(&self) -> Result<T> {
        self.try_recv()
    }
    fn recv(&self) -> Result<T> {
        self.recv()
    }
    fn is_alive(&self) -> bool {
        self.is_alive()
    }
}

/// Base channel implementation
pub struct BaseChannel<T: Sized, S: ChannelStorage<T>, M = RawMutex, CV = Condvar>(
    Arc<ChannelInner<T, S, M, CV>>,
)
where
    M: RawMutexTrait,
    CV: RawCondvar;

impl<T, S, M, CV> BaseChannel<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn id(&self) -> usize {
        self.0.id.as_usize()
    }
}

impl<T, S, M, CV> Eq for BaseChannel<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
}

impl<T, S, M, CV> PartialEq for BaseChannel<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl<T, S, M, CV> Clone for BaseChannel<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

struct ChannelInner<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    id: UniqueId,
    data: lock_api::Mutex<M, InnerData<T, S>>,
    data_available: CV,
    space_available: CV,
}

impl<T, S, M, CV> ChannelInner<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    fn send(&self, mut value: T) -> Result<()> {
        let mut data = self.data.lock();
        let pushed = loop {
            if data.receivers == 0 {
                return Err(Error::ChannelClosed);
            }
            let push_result = data.queue.try_push(value);
            let StorageTryPushOutput::Full(val) = push_result else {
                break push_result;
            };
            value = val;
            self.space_available.wait::<InnerData<T, S>, M>(&mut data);
        };
        match pushed {
            StorageTryPushOutput::Pushed => {
                self.data_available.notify_one();
                Ok(())
            }
            StorageTryPushOutput::Skipped => Err(Error::ChannelSkipped),
            StorageTryPushOutput::Full(_) => unreachable!(),
        }
    }
    fn send_timeout(&self, mut value: T, timeout: Duration) -> Result<()> {
        let mut pc = self.data.lock();
        let pushed = loop {
            if pc.receivers == 0 {
                return Err(Error::ChannelClosed);
            }
            let push_result = pc.queue.try_push(value);
            let StorageTryPushOutput::Full(val) = push_result else {
                break push_result;
            };
            value = val;
            if self
                .space_available
                .wait_for::<InnerData<T, S>, M>(&mut pc, timeout)
                .timed_out()
            {
                return Err(Error::Timeout);
            }
        };
        match pushed {
            StorageTryPushOutput::Pushed => {
                self.data_available.notify_one();
                Ok(())
            }
            StorageTryPushOutput::Skipped => Err(Error::ChannelSkipped),
            StorageTryPushOutput::Full(_) => unreachable!(),
        }
    }
    fn try_send(&self, value: T) -> Result<()> {
        let mut data = self.data.lock();
        if data.receivers == 0 {
            return Err(Error::ChannelClosed);
        }
        match data.queue.try_push(value) {
            StorageTryPushOutput::Pushed => {
                self.data_available.notify_one();
                Ok(())
            }
            StorageTryPushOutput::Skipped => Err(Error::ChannelSkipped),
            StorageTryPushOutput::Full(_) => Err(Error::ChannelFull),
        }
    }
    fn recv(&self) -> Result<T> {
        let mut data = self.data.lock();
        loop {
            if let Some(val) = data.queue.get() {
                self.space_available.notify_one();
                return Ok(val);
            } else if data.senders == 0 {
                return Err(Error::ChannelClosed);
            }
            self.data_available.wait::<InnerData<T, S>, M>(&mut data);
        }
    }
    fn recv_timeout(&self, timeout: Duration) -> Result<T> {
        let mut data = self.data.lock();
        loop {
            if let Some(val) = data.queue.get() {
                self.space_available.notify_one();
                return Ok(val);
            } else if data.senders == 0 {
                return Err(Error::ChannelClosed);
            }
            if self
                .data_available
                .wait_for::<InnerData<T, S>, M>(&mut data, timeout)
                .timed_out()
            {
                return Err(Error::Timeout);
            }
        }
    }
    fn try_recv(&self) -> Result<T> {
        let mut pc = self.data.lock();
        if let Some(val) = pc.queue.get() {
            self.space_available.notify_one();
            Ok(val)
        } else if pc.senders == 0 {
            Err(Error::ChannelClosed)
        } else {
            Err(Error::ChannelEmpty)
        }
    }
}

impl<T, S, M, CV> BaseChannel<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    /// Creates a new channel with the specified capacity and ordering
    pub fn new(capacity: usize, ordering: bool) -> Self {
        Self(
            ChannelInner {
                id: <_>::default(),
                data: lock_api::Mutex::const_new(M::INIT, InnerData::new(capacity, ordering)),
                data_available: CV::new(),
                space_available: CV::new(),
            }
            .into(),
        )
    }
}

struct InnerData<T, S>
where
    T: Sized,
    S: ChannelStorage<T>,
{
    queue: S,
    senders: usize,
    receivers: usize,
    _phantom: PhantomData<T>,
}

impl<T, S> InnerData<T, S>
where
    S: ChannelStorage<T>,
{
    fn new(capacity: usize, ordering: bool) -> Self {
        assert!(capacity > 0, "channel capacity MUST be > 0");
        Self {
            queue: S::with_capacity_and_ordering(capacity, ordering),
            senders: 1,
            receivers: 1,
            _phantom: PhantomData,
        }
    }
}

/// Base channel sender
#[derive(Eq, PartialEq)]
pub struct BaseSender<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    channel: BaseChannel<T, S, M, CV>,
}

impl<T, S, M, CV> BaseSender<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    /// Sends a value to the channel
    #[inline]
    pub fn send(&self, value: T) -> Result<()> {
        self.channel.0.send(value)
    }
    /// Sends a value to the channel with a timeout
    #[inline]
    pub fn send_timeout(&self, value: T, timeout: Duration) -> Result<()> {
        self.channel.0.send_timeout(value, timeout)
    }
    /// Tries to send a value to the channel (non-blocking)
    #[inline]
    pub fn try_send(&self, value: T) -> Result<()> {
        self.channel.0.try_send(value)
    }
    /// Returns the length of the channel storage
    #[inline]
    pub fn len(&self) -> usize {
        self.channel.0.data.lock().queue.len()
    }
    /// Returns true if the channel storage is full
    #[inline]
    pub fn is_full(&self) -> bool {
        self.channel.0.data.lock().queue.is_full()
    }
    /// Returns true if the channel storage is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.channel.0.data.lock().queue.is_empty()
    }
    /// Returns true if the channel is alive
    #[inline]
    pub fn is_alive(&self) -> bool {
        self.channel.0.data.lock().receivers > 0
    }
}

impl<T, S, M, CV> Clone for BaseSender<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn clone(&self) -> Self {
        self.channel.0.data.lock().senders += 1;
        Self {
            channel: self.channel.clone(),
        }
    }
}

impl<T, S, M, CV> Drop for BaseSender<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn drop(&mut self) {
        let mut pc = self.channel.0.data.lock();
        pc.senders -= 1;
        if pc.senders == 0 {
            self.channel.0.data_available.notify_all();
        }
    }
}

/// Base channel receiver
#[derive(Eq, PartialEq)]
pub struct BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    channel: BaseChannel<T, S, M, CV>,
}

impl<T, S, M, CV> Iterator for BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        self.recv().ok()
    }
}

impl<T, S, M, CV> BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar + RawCondvar<RawMutex = M>,
{
    /// Receives a value from the channel
    #[inline]
    pub fn recv(&self) -> Result<T> {
        self.channel.0.recv()
    }
    /// Receives a value from the channel with a timeout
    #[inline]
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T> {
        self.channel.0.recv_timeout(timeout)
    }
    /// Tries to receive a value from the channel (non-blocking)
    #[inline]
    pub fn try_recv(&self) -> Result<T> {
        self.channel.0.try_recv()
    }
    /// Returns the length of the channel storage
    #[inline]
    pub fn len(&self) -> usize {
        self.channel.0.data.lock().queue.len()
    }
    /// Returns true if the channel storage is full
    #[inline]
    pub fn is_full(&self) -> bool {
        self.channel.0.data.lock().queue.is_full()
    }
    /// Returns true if the channel storage is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.channel.0.data.lock().queue.is_empty()
    }
    /// Returns true if the channel is alive
    #[inline]
    pub fn is_alive(&self) -> bool {
        self.channel.0.data.lock().senders > 0
    }
}

impl<T, S, M, CV> Clone for BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn clone(&self) -> Self {
        self.channel.0.data.lock().receivers += 1;
        Self {
            channel: self.channel.clone(),
        }
    }
}

impl<T, S, M, CV> Drop for BaseReceiver<T, S, M, CV>
where
    T: Sized,
    S: ChannelStorage<T>,
    M: RawMutexTrait,
    CV: RawCondvar,
{
    fn drop(&mut self) {
        let mut pc = self.channel.0.data.lock();
        pc.receivers -= 1;
        if pc.receivers == 0 {
            self.channel.0.data_available.notify_all();
        }
    }
}

#[allow(clippy::type_complexity)]
pub(crate) fn make_channel<T: Sized, S: ChannelStorage<T>, M, CV>(
    ch: BaseChannel<T, S, M, CV>,
) -> (BaseSender<T, S, M, CV>, BaseReceiver<T, S, M, CV>)
where
    M: RawMutexTrait,
    CV: RawCondvar,
{
    let tx: BaseSender<T, S, M, CV> = BaseSender {
        channel: ch.clone(),
    };
    let rx: BaseReceiver<T, S, M, CV> = BaseReceiver { channel: ch };
    (tx, rx)
}