diff options
Diffstat (limited to 'src/util')
-rw-r--r-- | src/util/event.rs | 73 | ||||
-rw-r--r-- | src/util/mod.rs | 1 | ||||
-rw-r--r-- | src/util/serialization.rs | 18 |
3 files changed, 18 insertions, 74 deletions
diff --git a/src/util/event.rs b/src/util/event.rs deleted file mode 100644 index 379df99..0000000 --- a/src/util/event.rs +++ /dev/null @@ -1,73 +0,0 @@ -use std::io; -use std::sync::mpsc; -use std::thread; -use std::time::Duration; - -use termion::event::Key; -use termion::input::TermRead; - -pub enum Event<I> { - Input(I), - Tick, -} - -/// A small event handler that wrap termion input and tick events. Each event -/// type is handled in its own thread and returned to a common `Receiver` -pub struct Events { - rx: mpsc::Receiver<Event<Key>>, - input_handle: thread::JoinHandle<()>, - tick_handle: thread::JoinHandle<()>, -} - -#[derive(Debug, Clone, Copy)] -pub struct Config { - pub tick_rate: Duration, -} - -impl Default for Config { - fn default() -> Config { - Config { - tick_rate: Duration::from_millis(250), - } - } -} - -impl Events { - pub fn new() -> Events { - Events::with_config(Config::default()) - } - - pub fn with_config(config: Config) -> Events { - let (tx, rx) = mpsc::channel(); - let input_handle = { - let tx = tx.clone(); - thread::spawn(move || { - let stdin = io::stdin(); - for key in stdin.keys().flatten() { - if let Err(err) = tx.send(Event::Input(key)) { - eprintln!("{err}"); - return; - } - } - }) - }; - let tick_handle = { - thread::spawn(move || loop { - if let Err(err) = tx.send(Event::Tick) { - eprintln!("{err}"); - break; - } - thread::sleep(config.tick_rate); - }) - }; - Events { - rx, - input_handle, - tick_handle, - } - } - - pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> { - self.rx.recv() - } -} diff --git a/src/util/mod.rs b/src/util/mod.rs index c866e61..3444389 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -1,4 +1,3 @@ #[allow(dead_code)] -pub mod event; pub mod serialization; pub mod time; diff --git a/src/util/serialization.rs b/src/util/serialization.rs index 61b3a83..189a41a 100644 --- a/src/util/serialization.rs +++ b/src/util/serialization.rs @@ -8,3 +8,21 @@ pub fn line_to_words(line: &str) -> Vec<String> { pub fn words_to_line(words: &[String]) -> String { words.join(" | ") } + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn test_line_to_words() { + assert_eq!(line_to_words("a"), vec!("a")); + assert_eq!(line_to_words("a | b | c"), vec!("a", "b", "c")); + } + + #[test] + fn test_words_to_line() { + assert_eq!(words_to_line(&["a".to_string()]), "a"); + assert_eq!(words_to_line(&["a".to_string(), "b".to_string(), "c".to_string()]), "a | b | c"); + } +} |