selectables 0.1.1

Lock-free channels with a unified select! macro for recv and send arms
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
use selectables::*;
use std::{
    env, thread,
    time::{Duration, Instant},
};

// ════════════════════════════════════════════════════════════════════════════
// § 8.  Demonstrations
// ════════════════════════════════════════════════════════════════════════════

fn main() {
    unsafe { env::set_var("RUST_LOG", "trace") };
    minimal_logger::init().unwrap();

    demo_basic_select();
    demo_instant_default();
    demo_timeout_default();
    demo_after_as_recv_arm();
    demo_disconnection();
    demo_bounded_channel();
    demo_mpsc_bounded();
    demo_watch_channel();
    demo_bounded_broadcast();
    demo_oneshot_basic();
    demo_oneshot_select();
    demo_never();
    demo_priority_without_macro();
    demo_interval();

    minimal_logger::shutdown();
}

// ── Demo 1: Blocking select across two channels ───────────────────────────
fn demo_basic_select() {
    println!("\n╔══ Demo 1: blocking select across two channels ══╗");

    let (tx1, rx1) = unbounded_mpmc::channel::<&str>();
    let (tx2, rx2) = unbounded_mpmc::channel::<&str>();

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(30));
        tx1.send("hello from ch1").unwrap();
    });
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(10));
        tx2.send("hello from ch2").unwrap();
    });

    // Select twice — should receive from rx2 first (shorter delay), then rx1.
    for _ in 0..2 {
        select! {
            recv(rx1) -> msg => println!("  rx1 → {:?}", msg),
            recv(rx2) -> msg => println!("  rx2 → {:?}", msg),
        }
    }
}

// ── Demo 2: Non-blocking select with `default` ────────────────────────────
fn demo_instant_default() {
    println!("\n╔══ Demo 2: non-blocking select (instant default) ══╗");

    let (_tx, rx) = unbounded_mpmc::channel::<i32>(); // nothing will ever be sent

    select! {
        recv(rx) -> msg => println!("  got: {:?}", msg),
        default => println!("  nothing ready → took default branch"),
    }
}

// ── Demo 3: Timeout via `default(duration)` ───────────────────────────────
fn demo_timeout_default() {
    println!("\n╔══ Demo 3: select with timeout ══╗");

    let (_tx, rx) = unbounded_mpmc::channel::<i32>();

    let t0 = Instant::now();
    select! {
        recv(rx) -> msg => println!("  got: {:?}", msg),
        default(Duration::from_millis(50)) => {
            println!("  timed out after {:?}", t0.elapsed());
        },
    }
}

// ── Demo 4: `after(dur)` used as a regular recv arm ──────────────────────
fn demo_after_as_recv_arm() {
    println!("\n╔══ Demo 4: after() as a recv arm ══╗");

    let (tx, rx) = unbounded_mpmc::channel::<i32>();

    // Race: which fires first — the sender or the timer?
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(60));
        let _ = tx.send(42);
    });

    let timer1 = bounded_mpmc::after(Duration::from_millis(40)); // fires first
    let timer2 = bounded_mpsc::after(Duration::from_millis(40)); // fires first

    loop {
        select! {
            recv(rx)    -> msg => { println!("  data arrived: {:?}", msg); break; },
            recv(timer1) -> _   => println!("  timer1 fired before data"),
            recv(timer2) -> _   => println!("  timer2 fired before data"),
        }
    }
}

// ── Demo 5: Disconnection arrives through select ──────────────────────────
fn demo_disconnection() {
    println!("\n╔══ Demo 5: detecting sender disconnect ══╗");

    let (tx, rx) = unbounded_mpmc::channel::<i32>();
    drop(tx); // drop the only sender immediately

    select! {
        recv(rx) -> msg => println!("  result: {:?}", msg),  // Err(Disconnected)
        default(Duration::from_millis(100)) => println!("  timed out (unexpected)"),
    }
}

// ── Demo 6: Bounded channel with capacity limit ──────────────────────────
fn demo_bounded_channel() {
    println!("\n╔══ Demo 6: bounded channel capacity ══╗");

    let (tx, rx) = bounded_mpmc::channel::<i32>(2);

    tx.send(10).unwrap();
    tx.send(20).unwrap();
    let full = tx.send(30).err();

    println!("  sent 10, 20, send 30 full: {:?}", full.is_some());
    println!("  recv -> {:?}", rx.recv().unwrap());
    println!("  recv -> {:?}", rx.recv().unwrap());
}

// ── Demo 6.5: bounded MPSC channel with select! ══╗

fn demo_mpsc_bounded() {
    println!("\n╔══ Demo 6.5: bounded MPSC channel with select! ══╗");

    let (tx1, rx1) = bounded_mpsc::channel::<&str>(2);
    let (tx2, rx2) = bounded_mpsc::channel::<&str>(2);
    let (tx3, rx3) = bounded_mpsc::channel::<&usize>(2);

    let tx1_clone = tx1.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(10));
        let _ = tx1_clone.send("from mpsc1"); // receiver may have dropped; that's ok
    });

    let tx2_clone = tx2.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(20));
        let _ = tx2_clone.send("from mpsc2");
    });

    let tx3_clone = tx3.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(1));
        let _ = tx3_clone.send(&0);
    });

    loop {
        select! {
            recv(rx1) -> msg => println!("  rx1 → {:?}", msg),
            recv(rx2) -> msg => println!("  rx2 → {:?}", msg),
            recv(rx3) -> msg => println!("  rx3 → {:?}", msg),
            default(Duration::from_millis(50)) => {println!("  timed out"); break;},
        }
    }

    // Fill rx1 to test bounded behavior
    tx1.send("immediate").unwrap();
    tx1.send("second").unwrap();
    tx3.send(&1).unwrap();
    // This should fail since capacity is 2
    let full = tx1.send("blocked").err();
    println!("  mpsc1 full after send: {:?}", full.is_some());

    select! {
        recv(rx1) -> msg => println!("  rx1 → {:?}", msg),
        recv(rx2) -> msg => println!("  rx2 → {:?}", msg),
        recv(rx3) -> msg => println!("  rx3 → {:?}", msg),
    }

    // Now rx1 should be empty, try again
    select! {
        recv(rx1) -> msg => println!("  rx1 → {:?}", msg),
        recv(rx2) -> msg => println!("  rx2 → {:?}", msg),
        recv(rx3) -> msg => println!("  rx3 → {:?}", msg),
    }

    loop {
        select! {
            recv(rx1) -> msg => println!("  rx1 → {:?}", msg),
            recv(rx2) -> msg => println!("  rx2 → {:?}", msg),
            recv(rx3) -> msg => println!("  rx3 → {:?}", msg),
            default(Duration::from_millis(50)) => {println!("  timed out"); break;},
        }
    }

    let (tx1, rx1) = bounded_mpsc::channel::<i32>(1);
    let (tx2, rx2) = bounded_mpsc::channel::<String>(1);
    let (tx3, rx3) = bounded_mpsc::channel::<&i32>(1);

    // Demonstrate mixed-type recv arms: send to one, select picks it up.
    tx3.send(&42).unwrap();
    tx2.send("Hello".to_owned()).unwrap();
    tx1.send(42).unwrap();
    println!("\n  [mixed types]");
    loop {
        select! {
            recv(rx1) -> msg => println!("  i32  arm: {:?}", msg),
            recv(rx2) -> msg => {println!("  String arm: {:?}", msg);},
            recv(rx3) -> msg => {println!("  &i32 arm: {:?}", msg); break;},
        }
    }
}

// ── Demo 6.75: watch channel updates through recv arms ───────────────────
fn demo_watch_channel() {
    println!("\n╔══ Demo 6.75: watch channel updates ══╗");

    let (tx, rx) = watch::channel::<&str>();
    let tx_boot = tx.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(10));
        tx_boot.send("booting").unwrap();
    });

    println!(
        "  changed() -> version {:?}, value {:?}",
        rx.changed(),
        *rx.borrow()
    );

    let rx_for_select = rx.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(20));
        tx.send("ready").unwrap();
    });

    select! {
        recv(rx_for_select) -> version => println!("  select recv -> {:?}", version),
        default(Duration::from_millis(100)) => println!("  watch timed out"),
    }

    println!("  final value -> {:?}", *rx.borrow());
}

// ── Demo 6.85: bounded broadcast with lag detection ─────────────────────
fn demo_bounded_broadcast() {
    println!("\n╔══ Demo 6.85: bounded broadcast lag behavior + recovery ══╗");

    let (tx, rx1) = bounded_broadcast::channel::<i32>(2);
    let rx2 = rx1.clone();

    // Send 3 messages into a capacity-2 buffer: rx1 will lag
    tx.send(10).unwrap();
    tx.send(20).unwrap();
    tx.send(30).unwrap();

    // ─ Demonstrate lag detection
    println!("  rx1 first try_recv -> {:?}", rx1.try_recv());
    println!("    ^ Shows Lagged {{ skipped: 1 }} because buffer wrapped");

    // ─ Demonstrate automatic cursor recovery
    println!("  rx1 next recv -> {:?}", rx1.recv());
    println!("    ^ Cursor was auto-advanced; now receives oldest available (20)");

    // ─ New subscriber (rx2) starts at write position, sees future messages only
    println!("  rx2 first recv -> {:?}", rx2.recv());
    println!("    ^ rx2 subscribed after 30 was sent, so it won't see old messages");

    // ─ Demonstrate select! integration with lag handling
    let rx_sel = rx1.clone();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(20));
        let _ = tx.send(40);
    });

    select! {
        recv(rx_sel) -> msg => match msg {
            Ok(v) => println!("  select broadcast -> Ok({})", v),
            Err(e) => println!("  select broadcast -> Err({:?})", e),
        },
        default(Duration::from_millis(100)) => println!("  broadcast timed out"),
    }
}

// ── Demo 6.9: oneshot basics ─────────────────────────────────────────────
fn demo_oneshot_basic() {
    println!("\n╔══ Demo 6.9: oneshot basic send/recv ══╗");

    let (tx, rx) = oneshot::channel::<&str>();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(10));
        tx.send("delivered once").unwrap();
    });

    println!("  recv -> {:?}", rx.recv());
}

// ── Demo 6.95: oneshot in select! recv arms ─────────────────────────────
fn demo_oneshot_select() {
    println!("\n╔══ Demo 6.95: oneshot in select! recv arms ══╗");

    let (tx_data, rx_data) = unbounded_mpmc::channel::<i32>();
    let (tx_once, rx_once) = oneshot::channel::<&str>();

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(15));
        tx_once.send("oneshot won").unwrap();
    });

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(30));
        tx_data.send(99).unwrap();
    });

    select! {
        recv(rx_once) -> msg => println!("  oneshot -> {:?}", msg),
        recv(rx_data) -> msg => println!("  mpmc -> {:?}", msg),
        default(Duration::from_millis(100)) => println!("  timed out"),
    }
}

// ── Demo 7: never() disables an arm ──────────────────────────────────────
fn demo_never() {
    println!("\n╔══ Demo 7: never() disables an arm ══╗");

    let (tx, rx) = unbounded_mpmc::channel::<&str>();
    tx.send("real message").unwrap();

    // This arm is permanently not-ready; the `rx` arm wins.
    let phantom1: bounded_mpmc::Receiver<&str> = bounded_mpmc::never();

    // This arm is permanently not-ready; the `rx` arm wins.
    let phantom2: bounded_mpsc::Receiver<&str> = bounded_mpsc::never();

    select! {
        recv(phantom1) -> _ => println!("  phantom1 fired (impossible)"),
        recv(phantom2) -> _ => println!("  phantom2 fired (impossible)"),
        recv(rx)      -> m => println!("  real arm: {:?}", m),
    }
}

// ── Demo 7: Priority select without the macro ────────────────────────────
//
// `select!` rotates arms for fairness.  When you *always* want arm 0 to
// take precedence, call try_recv directly first, then fall back to select.
fn demo_priority_without_macro() {
    println!("\n╔══ Demo 7: manual priority select (no macro) ══╗");

    let (tx_hi, rx_hi) = unbounded_mpmc::channel::<&str>();
    let (tx_lo, rx_lo) = unbounded_mpmc::channel::<&str>();

    tx_hi.send("HIGH priority").unwrap();
    tx_lo.send("low priority").unwrap();

    // Drain hi-priority channel first.
    if let Ok(msg) = rx_hi.try_recv() {
        println!("  [hi] {}", msg);
    }

    // Fall back to the Select API (no macro) for the rest.
    let mut sel = Select::new();
    let i_hi = sel.recv(rx_hi.clone());
    let i_lo = sel.recv(rx_lo.clone());

    if let Some(oper) = sel.try_select() {
        match oper.index {
            i if i == i_hi => println!("  [hi] {:?}", rx_hi.complete_recv()),
            i if i == i_lo => println!("  [lo] {:?}", rx_lo.complete_recv()),
            _ => unreachable!(),
        }
    } else {
        println!("  nothing ready");
    }
}

// ── Demo 8: selectable interval ───────────────────────────────────────────
fn demo_interval() {
    println!("\n╔══ Demo 8: selectable interval ══╗");

    let iv = interval::interval(Duration::from_millis(50));
    let (tx, rx) = unbounded_mpmc::channel::<&str>();

    // Send a message after 125 ms — it should arrive between tick 2 and tick 4.
    thread::spawn({
        let tx = tx.clone();
        move || {
            thread::sleep(Duration::from_millis(125));
            tx.send("message between ticks").unwrap();
        }
    });

    for i in 0..10 {
        select! {
            recv(iv) -> tick => println!("  tick {} at {:?}", i, tick.unwrap()),
            recv(rx) -> msg  => println!("  msg: {:?}", msg.unwrap()),
        }
    }
}