Skip to content

Instantly share code, notes, and snippets.

@arthurbacci
Created April 9, 2021 22:17
Show Gist options
  • Save arthurbacci/6480df73f980e36787aa4ec17907670a to your computer and use it in GitHub Desktop.
Save arthurbacci/6480df73f980e36787aa4ec17907670a to your computer and use it in GitHub Desktop.
A example of async input using threads in Rust
use std::thread;
use std::sync::mpsc::{self, TryRecvError};
use std::io;
use std::time::Instant;
struct CircularIter<T> where T: Copy {
data: Vec<T>,
index: usize,
}
impl<T> CircularIter<T> where T: Copy {
fn new(data: Vec<T>) -> CircularIter<T> {
CircularIter {
data,
index: 0,
}
}
}
impl<T> Iterator for CircularIter<T> where T: Copy {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.data.len() == 0 {
None
} else {
self.index += 1;
if self.index >= self.data.len() {
self.index = 0;
}
Some(self.data[self.index])
}
}
}
fn main() {
let (tx1, rx1) = mpsc::channel();
let stdin = io::stdin();
thread::spawn(move || {
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
tx1.send(()).unwrap();
});
let progress = CircularIter::new(vec!["―", "\\", "|", "/"]);
println!();
'outer: for i in progress {
let st = Instant::now();
while st.elapsed().as_millis() < 250 {
match rx1.try_recv() {
Ok(_) => {
println!("\x1b[2A\x1b[KBye");
break 'outer;
}
Err(TryRecvError::Disconnected) => break 'outer,
_ => {}
}
}
println!("\x1b[1AWaiting for input {} ", i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment