summaryrefslogtreecommitdiffstats
path: root/vendor/crossbeam-channel/tests/iter.rs
blob: 463f3b0436730a9421807b0afadba23c6ffd0424 (plain)
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
//! Tests for iteration over receivers.

use crossbeam_channel::unbounded;
use crossbeam_utils::thread::scope;

#[test]
fn nested_recv_iter() {
    let (s, r) = unbounded::<i32>();
    let (total_s, total_r) = unbounded::<i32>();

    scope(|scope| {
        scope.spawn(move |_| {
            let mut acc = 0;
            for x in r.iter() {
                acc += x;
            }
            total_s.send(acc).unwrap();
        });

        s.send(3).unwrap();
        s.send(1).unwrap();
        s.send(2).unwrap();
        drop(s);
        assert_eq!(total_r.recv().unwrap(), 6);
    })
    .unwrap();
}

#[test]
fn recv_iter_break() {
    let (s, r) = unbounded::<i32>();
    let (count_s, count_r) = unbounded();

    scope(|scope| {
        scope.spawn(move |_| {
            let mut count = 0;
            for x in r.iter() {
                if count >= 3 {
                    break;
                } else {
                    count += x;
                }
            }
            count_s.send(count).unwrap();
        });

        s.send(2).unwrap();
        s.send(2).unwrap();
        s.send(2).unwrap();
        let _ = s.send(2);
        drop(s);
        assert_eq!(count_r.recv().unwrap(), 4);
    })
    .unwrap();
}

#[test]
fn recv_try_iter() {
    let (request_s, request_r) = unbounded();
    let (response_s, response_r) = unbounded();

    scope(|scope| {
        scope.spawn(move |_| {
            let mut count = 0;
            loop {
                for x in response_r.try_iter() {
                    count += x;
                    if count == 6 {
                        return;
                    }
                }
                request_s.send(()).unwrap();
            }
        });

        for _ in request_r.iter() {
            if response_s.send(2).is_err() {
                break;
            }
        }
    })
    .unwrap();
}

#[test]
fn recv_into_iter_owned() {
    let mut iter = {
        let (s, r) = unbounded::<i32>();
        s.send(1).unwrap();
        s.send(2).unwrap();
        r.into_iter()
    };

    assert_eq!(iter.next().unwrap(), 1);
    assert_eq!(iter.next().unwrap(), 2);
    assert!(iter.next().is_none());
}

#[test]
fn recv_into_iter_borrowed() {
    let (s, r) = unbounded::<i32>();
    s.send(1).unwrap();
    s.send(2).unwrap();
    drop(s);

    let mut iter = (&r).into_iter();
    assert_eq!(iter.next().unwrap(), 1);
    assert_eq!(iter.next().unwrap(), 2);
    assert!(iter.next().is_none());
}