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
use anomaly::BoxError;
use crossbeam_channel::{Receiver, Select};

pub fn try_recv_multiple<K, T>(rs: &[(K, Receiver<T>)]) -> Option<(&K, T)> {
    // Build a list of operations.
    let mut sel = Select::new();
    for (_, r) in rs {
        sel.recv(r);
    }

    // Complete the selected operation.
    let oper = sel.try_select().ok()?;
    let index = oper.index();

    // Get the receiver who is ready
    let (k, r) = &rs[index];

    // Receive the message
    let result = oper.recv(r).ok()?;

    Some((k, result))
}

pub fn recv_multiple<K, T>(rs: &[(K, Receiver<T>)]) -> Result<(&K, T), BoxError> {
    // Build a list of operations.
    let mut sel = Select::new();
    for (_, r) in rs {
        sel.recv(r);
    }

    // Complete the selected operation.
    let oper = sel.select();
    let index = oper.index();

    // Get the receiver who is ready
    let (k, r) = &rs[index];

    // Receive the message
    let result = oper.recv(r)?;

    Ok((k, result))
}