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