1*536cf88cSTrevor Elliott use test_programs::wasi::cli::{stdin, stdout};
2*536cf88cSTrevor Elliott 
main()3*536cf88cSTrevor Elliott fn main() {
4*536cf88cSTrevor Elliott     match std::env::var("PIPED_SIDE")
5*536cf88cSTrevor Elliott         .expect("piped tests require the PIPED_SIDE env var")
6*536cf88cSTrevor Elliott         .as_str()
7*536cf88cSTrevor Elliott     {
8*536cf88cSTrevor Elliott         "PRODUCER" => producer(),
9*536cf88cSTrevor Elliott         "CONSUMER" => consumer(),
10*536cf88cSTrevor Elliott         side => panic!("unknown piped test side: {side}"),
11*536cf88cSTrevor Elliott     }
12*536cf88cSTrevor Elliott }
13*536cf88cSTrevor Elliott 
producer()14*536cf88cSTrevor Elliott fn producer() {
15*536cf88cSTrevor Elliott     let out = stdout::get_stdout();
16*536cf88cSTrevor Elliott     let out_pollable = out.subscribe();
17*536cf88cSTrevor Elliott 
18*536cf88cSTrevor Elliott     for i in 1..100 {
19*536cf88cSTrevor Elliott         let message = format!("{i}");
20*536cf88cSTrevor Elliott         loop {
21*536cf88cSTrevor Elliott             let available = out.check_write().unwrap() as usize;
22*536cf88cSTrevor Elliott             if available >= message.len() {
23*536cf88cSTrevor Elliott                 break;
24*536cf88cSTrevor Elliott             }
25*536cf88cSTrevor Elliott 
26*536cf88cSTrevor Elliott             out_pollable.block();
27*536cf88cSTrevor Elliott             assert!(out_pollable.ready());
28*536cf88cSTrevor Elliott         }
29*536cf88cSTrevor Elliott 
30*536cf88cSTrevor Elliott         out.write(message.as_bytes()).unwrap()
31*536cf88cSTrevor Elliott     }
32*536cf88cSTrevor Elliott 
33*536cf88cSTrevor Elliott     drop(out_pollable);
34*536cf88cSTrevor Elliott }
35*536cf88cSTrevor Elliott 
consumer()36*536cf88cSTrevor Elliott fn consumer() {
37*536cf88cSTrevor Elliott     let stdin = stdin::get_stdin();
38*536cf88cSTrevor Elliott     let stdin_pollable = stdin.subscribe();
39*536cf88cSTrevor Elliott 
40*536cf88cSTrevor Elliott     for i in 1..100 {
41*536cf88cSTrevor Elliott         let expected = format!("{i}");
42*536cf88cSTrevor Elliott 
43*536cf88cSTrevor Elliott         stdin_pollable.block();
44*536cf88cSTrevor Elliott         assert!(stdin_pollable.ready());
45*536cf88cSTrevor Elliott 
46*536cf88cSTrevor Elliott         let bytes = stdin.read(expected.len() as u64).unwrap();
47*536cf88cSTrevor Elliott         assert_eq!(&bytes, expected.as_bytes());
48*536cf88cSTrevor Elliott     }
49*536cf88cSTrevor Elliott 
50*536cf88cSTrevor Elliott     drop(stdin_pollable);
51*536cf88cSTrevor Elliott }
52