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