Skip to main content

interop/
interop.rs

1use cloudtoid_interprocess::{Options, Publisher, Subscriber};
2use std::{
3    io::{self, Write},
4    time::Duration,
5};
6fn message(i: usize) -> Vec<u8> {
7    let mut data = vec![0; if i % 251 == 250 { 4088 } else { 8 + i % 251 }];
8    data[..8].copy_from_slice(&(i as u64).to_le_bytes());
9    for (j, byte) in data.iter_mut().enumerate().skip(8) {
10        *byte = ((i + j) % 251) as u8;
11    }
12    data
13}
14fn main() {
15    let args = std::env::args().collect::<Vec<_>>();
16    let options = Options::new(
17        &args[2],
18        std::env::var("INTEROP_CAPACITY")
19            .map(|v| v.parse().unwrap())
20            .unwrap_or(4096),
21    )
22    .with_path(&args[3]);
23    let count = args[4].parse::<usize>().unwrap();
24    if args[1].starts_with("hold-") {
25        let _publisher;
26        let _subscriber;
27        if args[1] == "hold-publisher" {
28            _publisher = Publisher::open(&options).unwrap();
29        } else {
30            _subscriber = Subscriber::open(&options).unwrap();
31        }
32        println!("READY");
33        io::stdout().flush().unwrap();
34        io::stdin().read_line(&mut String::new()).unwrap();
35    } else if args[1] == "publish" {
36        let publisher = Publisher::open(&options).unwrap();
37        let start = args.get(5).map_or(0, |s| s.parse::<usize>().unwrap());
38        if args.len() > 5 {
39            println!("READY");
40            io::stdout().flush().unwrap();
41            io::stdin().read_line(&mut String::new()).unwrap();
42        }
43        for i in start..start + count {
44            let data = message(i);
45            while let Err(error) = publisher.try_send(&data) {
46                assert!(error.is_full(), "{error}");
47                std::thread::yield_now();
48            }
49        }
50    } else {
51        let subscriber = Subscriber::open(&options).unwrap();
52        println!("READY");
53        if args[1] == "collect" {
54            loop {
55                let data = subscriber
56                    .recv_timeout(Duration::from_secs(30))
57                    .unwrap()
58                    .unwrap();
59                if data.is_empty() {
60                    break;
61                }
62                let id = u64::from_le_bytes(data[..8].try_into().unwrap()) as usize;
63                assert_eq!(data, message(id));
64                println!("{id}");
65            }
66            return;
67        }
68        for i in 0..count {
69            assert_eq!(
70                subscriber
71                    .recv_timeout(Duration::from_secs(30))
72                    .unwrap()
73                    .unwrap(),
74                message(i)
75            );
76        }
77    }
78}