unbounded-spsc 0.3.0

An unbounded spsc queue built from `bounded_spsc_queue`s
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
519
520
521
522
523
524
525
526
527
528
#![allow(dead_code)]

use std;
use crate::{blocking, Receiver, RecvError, SelectionResult};

/// A "receiver set" structure used to manage a set of receivers being selected
/// over.
pub(crate) struct Select {
  inner   : std::cell::UnsafeCell <Inner>,
  next_id : std::cell::Cell <usize>
}
impl !Send for Select {}

/// Handle to a receiver which is currently a member of a `Select` set of
/// receivers, used to keep the receiver in the set as well as to interact
/// with the underlying receiver.
pub(crate) struct Handle <'rx, T : Send> {
  /// The ID of this handle, used to compare against the return value of
  /// `Select:::wait()`
  id       : usize,
  selector : *mut Inner,
  next     : *mut Handle <'static, ()>,
  prev     : *mut Handle <'static, ()>,
  added    : bool,
  packet   : &'rx (dyn Packet + 'rx),
  // due to our fun transmutes, be sure to place this at the end. (nothing
  // previous relies on T)
  rx       : &'rx Receiver <T>
}

struct Inner {
  head : *mut Handle <'static, ()>,
  tail : *mut Handle <'static, ()>
}

struct HandleIter {
  cur : *mut Handle <'static, ()>
}

#[derive(PartialEq, Eq)]
pub(crate) enum StartResult {
  Installed,
  Abort
}

pub(crate) trait Packet {
  fn can_recv        (&self) -> bool;
  fn start_selection (&self, token : std::sync::Arc <blocking::Inner>)
    -> StartResult;
  fn abort_selection (&self) -> bool;
}

impl Select {
  /// New empty selection structure.
  pub(crate) const fn new () -> Select {
    Select {
      inner: std::cell::UnsafeCell::new (Inner {
        head: std::ptr::null_mut(),
        tail: std::ptr::null_mut()
      }),
      next_id: std::cell::Cell::new (1)
    }
  }

  /// New handle into this receiver set for a new receiver; does *not* add the
  /// receiver to the receiver set, for that call `add` on the handle itself.
  pub(crate) fn handle <'a, T> (&'a self, rx : &'a Receiver <T>) -> Handle <'a, T>
    where T : Send
  {
    let id = self.next_id.get();
    self.next_id.set (id + 1);
    Handle {
      id,
      selector: self.inner.get(),
      next:     std::ptr::null_mut(),
      prev:     std::ptr::null_mut(),
      added:    false,
      rx,
      packet:   rx
    }
  }

  /// Wait for an "event" on this receiver set. Returns an ID that can be
  /// queried against any active `Handle` structures `id` method. The handle
  /// with the matching `id` will have some sort of "event" available on it:
  /// either that data is available or the corresponding channel has been
  /// closed.
  pub(crate) fn wait (&self) -> usize {
    self.wait2 (true)
  }

  /// Helper method for skipping the "preflight checks" during testing
  fn wait2 (&self, do_preflight_checks : bool) -> usize {
    unsafe {
      // Stage 1: preflight checks
      if do_preflight_checks {
        for handle in self.iter() {
          if (*handle).packet.can_recv() {
            return (*handle).id();
          }
        }
      }
      // Stage 2: begin blocking process
      let (wait_token, signal_token) = blocking::tokens();
      for (i, handle) in self.iter().enumerate() {
        match (*handle).packet.start_selection (signal_token.clone()) {
          StartResult::Installed => {}
          StartResult::Abort     => {
            for handle in self.iter().take (i) {
              (*handle).packet.abort_selection();
            }
            return (*handle).id;
          }
        }
      }
      // Stage 3: no message availble, actually block
      wait_token.wait();
      // Stage 4: must be a message; find it
      let mut ready_id = usize::MAX;
      for handle in self.iter() {
        if (*handle).packet.abort_selection() {
          ready_id = (*handle).id;
        }
      }

      // must have found a ready receiver
      assert_ne!(ready_id, usize::MAX);
      ready_id
    }
  }

  fn iter (&self) -> HandleIter {
    HandleIter {
      cur: unsafe { &*self.inner.get() }.head
    }
  }
}

impl std::fmt::Debug for Select {
  fn fmt (&self, f : &mut std::fmt::Formatter) -> std::fmt::Result {
    write!(f, "Select {{ .. }}")
  }
}

impl Drop for Select {
  fn drop (&mut self) {
    unsafe {
      assert!((&*self.inner.get()).head.is_null());
      assert!((&*self.inner.get()).tail.is_null());
    }
  }
}

impl <'rx, T> Handle <'rx, T> where T : Send {
  #[inline]
  pub(crate) const fn id (&self) -> usize {
    self.id
  }

  pub(crate) fn recv (&self) -> Result <T, RecvError> {
    self.rx.recv()
  }

  /// Add this handle to the receiver set that the handle was created from.
  pub(crate) unsafe fn add (&mut self) {
    if self.added {
      return
    }

    let selector = unsafe { &mut *self.selector };
    let me = std::ptr::from_mut::<Handle <'rx, T>> (self) as *mut Handle <'static, ()>;
    if selector.head.is_null() {
      selector.head = me;
    } else {
      unsafe {
        (*me).prev = selector.tail;
        assert!((*me).next.is_null());
        (*selector.tail).next = me;
      }
    }
    selector.tail = me;

    self.added = true;
  }

  /// Remove this handle from the receiver set.
  pub(crate) unsafe fn remove (&mut self) {
    if !self.added {
      return
    }

    let selector = unsafe { &mut *self.selector };
    let me = std::ptr::from_mut::<Handle <'rx, T>>(self) as *mut Handle <'static, ()>;
    if self.prev.is_null() {
      assert_eq!(selector.head, me);
      selector.head = self.next;
    } else {
      unsafe { (*self.prev).next = self.next; }
    }
    if self.next.is_null() {
      assert_eq!(selector.tail, me);
      selector.tail = self.prev;
    } else {
      unsafe { (*self.next).prev = self.prev; }
    }

    self.next = std::ptr::null_mut();
    self.prev = std::ptr::null_mut();
    self.added = false;
  }
}

impl <'rx, T> std::fmt::Debug for Handle <'rx, T> where T : Send + 'rx {
  fn fmt (&self, f : &mut std::fmt::Formatter) -> std::fmt::Result {
    write!(f, "Handle {{ .. }}")
  }
}

impl <T> Drop for Handle <'_, T> where T : Send {
  fn drop (&mut self) {
    unsafe { self.remove() }
  }
}

impl Iterator for HandleIter {
  type Item = *mut Handle <'static, ()>;
  fn next (&mut self) -> Option <*mut Handle <'static, ()>> {
    if self.cur.is_null() {
      None
    } else {
      let ret = Some (self.cur);
      unsafe {
        self.cur = (*self.cur).next;
      }
      ret
    }
  }
}

impl <T> Packet for Receiver <T> {
  #[inline]
  fn can_recv (&self) -> bool {
    self.can_recv_()
  }
  fn start_selection (&self, token : std::sync::Arc <blocking::Inner>)
    -> StartResult
  {
    match self.start_selection_ (token) {
      SelectionResult::SelSuccess  => StartResult::Installed,
      SelectionResult::SelCanceled => StartResult::Abort
    }
  }
  #[inline]
  fn abort_selection (&self) -> bool {
    self.abort_selection_()
  }
}

#[macro_export]
macro_rules! select {
  (
    $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
  ) => {{
    let sel = Select::new();
    $(
    let mut $rx = sel.handle (&$rx);
    )+
    unsafe {
      $($rx.add();)+
    }
    let ret = sel.wait();
    $(
    if ret == $rx.id() {
      let $name = $rx.$meth(); $code
    } else
    )+
    { unreachable!() }
  }}
}

#[cfg(test)]
mod tests {
  use super::*;
  use super::super::*;

  #[test]
  fn smoke() {
    let (tx1, rx1) = channel::<i32>();
    let (tx2, rx2) = channel::<i32>();
    tx1.send (1).unwrap();
    select! {
      foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); },
      _bar = rx2.recv() => panic!()
    }
    tx2.send (2).unwrap();
    select! {
      _foo = rx1.recv() => panic!(),
      bar = rx2.recv() => assert_eq!(bar.unwrap(), 2)
    }
    drop(tx1);
    select! {
      foo = rx1.recv() => { foo.unwrap_err(); },
      _bar = rx2.recv() => panic!()
    }
    drop(tx2);
    select! {
      bar = rx2.recv() => { bar.unwrap_err(); }
    }
  }

  #[test]
  fn smoke2() {
    let (_tx1, rx1) = channel::<i32>();
    let (_tx2, rx2) = channel::<i32>();
    let (_tx3, rx3) = channel::<i32>();
    let (_tx4, rx4) = channel::<i32>();
    let (tx5, rx5) = channel::<i32>();
    tx5.send (4).unwrap();
    select! {
      _foo = rx1.recv() => panic!("1"),
      _foo = rx2.recv() => panic!("2"),
      _foo = rx3.recv() => panic!("3"),
      _foo = rx4.recv() => panic!("4"),
      foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); }
    }
  }

  #[test]
  fn closed() {
    let (_tx1, rx1) = channel::<i32>();
    let (tx2, rx2) = channel::<i32>();
    drop(tx2);

    select! {
      _a1 = rx1.recv() => panic!(),
      a2 = rx2.recv() => { a2.unwrap_err(); }
    }
  }

  #[test]
  fn unblocks() {
    let (tx1, rx1) = channel::<i32>();
    let (_tx2, rx2) = channel::<i32>();
    let (tx3, rx3) = channel::<i32>();

    let _t = std::thread::spawn(move|| {
      for _ in 0..20 { std::thread::yield_now(); }
      tx1.send (1).unwrap();
      rx3.recv().unwrap();
      for _ in 0..20 { std::thread::yield_now(); }
    });

    select! {
      a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
      _b = rx2.recv() => panic!()
    }
    tx3.send (1).unwrap();
    select! {
      a = rx1.recv() => assert!(a.is_err()),
      _b = rx2.recv() => panic!()
    }
  }

  #[test]
  fn both_ready() {
    let (tx1, rx1) = channel::<i32>();
    let (tx2, rx2) = channel::<i32>();
    let (tx3, rx3) = channel::<bool>();

    let _t = std::thread::spawn(move|| {
      for _ in 0..20 { std::thread::yield_now(); }
      tx1.send (1).unwrap();
      tx2.send (2).unwrap();
      rx3.recv().unwrap();
    });

    select! {
      a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
      a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
    }
    select! {
      a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
      a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
    }
    assert_eq!(rx1.try_recv(), Err (TryRecvError::Empty));
    assert_eq!(rx2.try_recv(), Err (TryRecvError::Empty));
    tx3.send (true).unwrap();
  }

  #[test]
  fn stress() {
    const AMT: i32 = 10000;
    let (tx1, rx1) = channel::<i32>();
    let (tx2, rx2) = channel::<i32>();
    let (tx3, rx3) = channel::<bool>();

    let _t = std::thread::spawn(move|| {
      for i in 0..AMT {
        if i % 2 == 0 {
          tx1.send (i).unwrap();
        } else {
          tx2.send (i).unwrap();
        }
        rx3.recv().unwrap();
      }
    });

    for i in 0..AMT {
      select! {
        i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); },
        i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); }
      }
      tx3.send (true).unwrap();
    }
  }

  #[test]
  fn preflight1() {
    let (tx, rx) = channel();
    tx.send (true).unwrap();
    select! {
      _n = rx.recv() => {}
    }
  }

  #[test]
  fn preflight2() {
    let (tx, rx) = channel();
    tx.send (true).unwrap();
    tx.send (true).unwrap();
    select! {
      _n = rx.recv() => {}
    }
  }

  #[test]
  fn preflight4() {
    let (tx, rx) = channel();
    tx.send (true).unwrap();
    let s = Select::new();
    let mut h = s.handle (&rx);
    unsafe { h.add(); }
    assert_eq!(s.wait2 (false), h.id);
  }

  #[test]
  fn preflight5() {
    let (tx, rx) = channel();
    tx.send (true).unwrap();
    tx.send (true).unwrap();
    let s = Select::new();
    let mut h = s.handle(&rx);
    unsafe { h.add(); }
    assert_eq!(s.wait2 (false), h.id);
  }

  #[test]
  fn preflight7() {
    let (tx, rx) = channel::<bool>();
    drop(tx);
    let s = Select::new();
    let mut h = s.handle(&rx);
    unsafe { h.add(); }
    assert_eq!(s.wait2 (false), h.id);
  }

  #[test]
  fn preflight8() {
    let (tx, rx) = channel();
    tx.send (true).unwrap();
    drop(tx);
    rx.recv().unwrap();
    let s = Select::new();
    let mut h = s.handle(&rx);
    unsafe { h.add(); }
    assert_eq!(s.wait2 (false), h.id);
  }

  #[test]
  fn oneshot_data_waiting() {
    let (tx1, rx1) = channel();
    let (tx2, rx2) = channel();
    let _t = std::thread::spawn(move|| {
      select! {
        _n = rx1.recv() => {}
      }
      tx2.send (true).unwrap();
    });

    for _ in 0..100 { std::thread::yield_now() }
    tx1.send (true).unwrap();
    rx2.recv().unwrap();
  }

  #[test]
  fn stream_data_waiting() {
    let (tx1, rx1) = channel();
    let (tx2, rx2) = channel();
    tx1.send (true).unwrap();
    tx1.send (true).unwrap();
    rx1.recv().unwrap();
    rx1.recv().unwrap();
    let _t = std::thread::spawn(move|| {
      select! {
        _n = rx1.recv() => {}
      }
      tx2.send (true).unwrap();
    });

    for _ in 0..100 { std::thread::yield_now() }
    tx1.send (true).unwrap();
    rx2.recv().unwrap();
  }

  #[test]
  fn fmt_debug_select() {
    let sel = Select::new();
    assert_eq!(format!("{sel:?}"), "Select { .. }");
  }

  #[test]
  fn fmt_debug_handle() {
    let (_, rx) = channel::<i32>();
    let sel = Select::new();
    let handle = sel.handle(&rx);
    assert_eq!(format!("{handle:?}"), "Handle { .. }");
  }
}