message/
message.rs

1extern crate ringbuf_basedrop;
2
3use std::io::Read;
4use std::thread;
5use std::time::Duration;
6
7use basedrop::Collector;
8use ringbuf_basedrop::RingBuffer;
9
10fn main() {
11    let collector = Collector::new();
12
13    let buf = RingBuffer::<u8>::new(10);
14    let (mut prod, mut cons) = buf.split(&collector.handle());
15
16    let smsg = "The quick brown fox jumps over the lazy dog";
17
18    let pjh = thread::spawn(move || {
19        println!("-> sending message: '{}'", smsg);
20
21        let zero = [0];
22        let mut bytes = smsg.as_bytes().chain(&zero[..]);
23        loop {
24            if prod.is_full() {
25                println!("-> buffer is full, waiting");
26                thread::sleep(Duration::from_millis(1));
27            } else {
28                let n = prod.read_from(&mut bytes, None).unwrap();
29                if n == 0 {
30                    break;
31                }
32                println!("-> {} bytes sent", n);
33            }
34        }
35
36        println!("-> message sent");
37    });
38
39    let cjh = thread::spawn(move || {
40        println!("<- receiving message");
41
42        let mut bytes = Vec::<u8>::new();
43        loop {
44            if cons.is_empty() {
45                if bytes.ends_with(&[0]) {
46                    break;
47                } else {
48                    println!("<- buffer is empty, waiting");
49                    thread::sleep(Duration::from_millis(1));
50                }
51            } else {
52                let n = cons.write_into(&mut bytes, None).unwrap();
53                println!("<- {} bytes received", n);
54            }
55        }
56
57        assert_eq!(bytes.pop().unwrap(), 0);
58        let msg = String::from_utf8(bytes).unwrap();
59        println!("<- message received: '{}'", msg);
60
61        msg
62    });
63
64    pjh.join().unwrap();
65    let rmsg = cjh.join().unwrap();
66
67    assert_eq!(smsg, rmsg);
68}