rustyline 19.0.0

Rustyline, a readline implementation based on Antirez's Linenoise
Documentation
use std::borrow::Cow::{self, Borrowed, Owned};

use rustyline::config::Configurer as _;
use rustyline::highlight::{CmdKind, Highlighter};
use rustyline::{ColorMode, Completer, Editor, Helper, Hinter, Result, Validator};

#[derive(Completer, Default, Helper, Hinter, Validator)]
struct MaskingHighlighter {
    masking: bool,
}

impl Highlighter for MaskingHighlighter {
    fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
        use unicode_width::UnicodeWidthStr as _;
        if self.masking {
            Owned(" ".repeat(line.width()))
        } else {
            Borrowed(line)
        }
    }

    fn highlight_char(&self, _line: &str, _pos: usize, kind: CmdKind) -> bool {
        match kind {
            CmdKind::MoveCursor => false,
            _ => self.masking,
        }
    }
}

fn main() -> Result<()> {
    env_logger::init();
    println!("This is just a hack. Reading passwords securely requires more than that.");
    let mut rl = Editor::<MaskingHighlighter, _>::default()?;

    let username = rl.readline("Username: ")?;
    println!("Username is {username}");

    rl.helper_mut().expect("No helper").masking = true;
    rl.set_color_mode(ColorMode::Forced); // force masking
    rl.set_auto_add_history(false); // make sure password is not added to history
    let mut guard = rl.set_cursor_visibility(false)?;
    let passwd = rl.readline("Password: ")?;
    guard.take();
    println!("Secret is {passwd}");
    Ok(())
}