async_command/
lib.rs

1extern crate rusting;
2use rusting::Rust;
3
4use std::thread;
5use std::process::{Command, Stdio};
6use std::io::{BufReader, Write, BufRead};
7use std::sync::mpsc::{Sender, Receiver, channel};
8
9pub struct AsyncCommand {
10	process: std::process::Child,
11	tx: Sender<Option<String>>,
12	rx: Receiver<Option<String>>,
13}
14
15fn e<T: ::std::fmt::Display>(e: T) { println!("doesn't rust: {}", e); }
16fn o() { println!("no rusting for empty options"); }
17
18impl AsyncCommand {
19	pub fn new(c: &mut Command) -> AsyncCommand {
20		let process = c
21			.stdin(Stdio::piped())
22			.stdout(Stdio::piped())
23			.spawn()
24			.rust(e);
25
26		let (tx, rx) = channel();
27		
28		AsyncCommand {
29			process: process,
30			tx: tx,
31			rx: rx,
32		}
33	}
34
35	pub fn run(&mut self) {
36		let tx = self.tx.clone();
37		let stdout = self.process.stdout.take().rust(o);
38
39		thread::spawn(move || {
40			let reader = BufReader::new(stdout);
41
42			for line in reader.lines() {
43				tx.send(Some(line.rust(e))).rust(e);
44			}
45		});
46	}
47
48	pub fn push(&mut self, buf: &[u8]) {
49		let stdin = self.process.stdin.as_mut().rust(o);
50
51		stdin.write(buf).rust(e);
52		stdin.flush().rust(e);
53	}
54
55	pub fn packets(&mut self) -> AsyncCommandIntoIterator {
56		AsyncCommandIntoIterator {
57			subprocess: self,
58		}
59	}
60}
61
62pub struct AsyncCommandIntoIterator<'a> {
63	subprocess: &'a mut AsyncCommand,
64}
65
66impl <'a>Iterator for AsyncCommandIntoIterator<'a> {
67	type Item = String;
68	fn next(&mut self) -> Option<String> {
69		let data = self.subprocess.rx.try_recv();
70		if data.is_ok() {
71			data.rust(e)
72		} else { None }
73	}
74}