0

I'm writing an ncurses app with Rust.

When the user inputs a valid UTF-8 char (like ć, or some Asian letters), I want to build up a search string from it and print it to screen. Currently I have this:

use ncurses::*;

fn main() {
    ...
    let mut search_string = String::new();
    ...
    loop {
        let user_input = getch();
        match user_input {
            27 => break,
            KEY_UP => { ... },
            KEY_DOWN => { ... },
            KEY_BACKSPACE => { ... },
            _ => {
                search_string += &std::char::from_u32(user_input as u32).expect("Invalid char.").to_string();
                mvaddstr(0, 0, &search_string);
                app::autosearch();
            }
        }
    }
}

However, this catches all other keys, such as F5, KEY_LEFT, etc.

How can I match only valid UTF-8 letters?

adder
  • 3,512
  • 1
  • 16
  • 28

2 Answers2

0

If getch gives you a u8, you could collect subsequent key presses into a Vec<u8> and then call e.g. from_utf8 on each getch, handling the error as appropriate (see Utf8Error for more info).

phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • I'm not sure how many times should I call `getch()`, and where. Is there like a null byte that `getch()` returns so I can stop calling `getch()` when I encounter such a thing? I think you really should show a code example. Thanks in advance. – adder Apr 19 '20 at 12:34
  • As a start, you could just call `from_utf8` on each char, and try to find out from the potential `Utf8Error` how often you need to call it. – phimuemue Apr 19 '20 at 16:13
0

In C, you could call get_wch() instead of getch() -- it returns KEY_CODE_YES for KEY_* codes, while the actual key is stored to an address passed as a parameter. But I don't know how this translates to Rust.

William McBrine
  • 2,166
  • 11
  • 7