console-input 0.2.0

A simple library to help handle keyboard presses in a console
Documentation
pub use crossterm::event::{self, Event};
use crossterm::event::{poll, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use std::time::Duration;

mod raw_mode;
pub use raw_mode::{disable as disable_raw_mode, enable as enable_raw_mode, exit as exit_raw_mode};

/// Get an [`Event`]. When raw mode is disabled, the input will only be registered after enter is pressed. Call [`enable_raw_mode()`] at the beginning of the program to avoid having to press enter
#[must_use]
pub fn read() -> Option<Event> {
    event::read().ok()
}

/// Get an [`Event`], without blocking. When raw mode is disabled, the input will only be registered after enter is pressed. Call [`enable_raw_mode()`] at the beginning of the program to avoid having to press enter
#[must_use]
pub fn read_non_blocking() -> Option<Event> {
    match poll(Duration::ZERO) {
        Ok(true) => read(),
        _ => None,
    }
}

/// If the event is a `Ctrl+C` (Keyboard Interrupt), exit immediately.
///
/// ## Example
/// ```
/// # use console_input::keypress;
/// # let event = keypress::read_non_blocking();
/// // Will get the input but exit the process if the input was `Ctrl+C`
/// keypress::exit_if_kb_interrupt(&event);
/// ```
pub fn exit_if_kb_interrupt(event: &Option<Event>) {
    if matches!(
        event,
        Some(Event::Key(KeyEvent {
            code: KeyCode::Char('c'),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            ..
        }))
    ) {
        exit_raw_mode();
    }
}

/// Get an input, with or without blocking, and exit if the input is a keyboard interrupt (Ctrl+C)
///
/// ## Example
/// ```
/// # use console_input::keypress;
/// // Will get the input without blocking, but exit the process if the input was `Ctrl+C`
/// let event = keypress::read_and_handle_kb_interrupt(false);
/// ```
#[must_use]
pub fn read_and_handle_kb_interrupt(blocking: bool) -> Option<Event> {
    let event = if blocking {
        read()
    } else {
        read_non_blocking()
    };
    exit_if_kb_interrupt(&event);
    event
}