File: input_validation.rs

package info (click to toggle)
rust-rustyline 17.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,032 kB
  • sloc: makefile: 2
file content (31 lines) | stat: -rw-r--r-- 918 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use rustyline::validate::{ValidationContext, ValidationResult, Validator};
use rustyline::{Completer, Helper, Highlighter, Hinter};
use rustyline::{Editor, Result};

#[derive(Completer, Helper, Highlighter, Hinter)]
struct InputValidator {}

impl Validator for InputValidator {
    fn validate(&self, ctx: &mut ValidationContext) -> Result<ValidationResult> {
        use ValidationResult::{Incomplete, Invalid, Valid};
        let input = ctx.input();
        let result = if !input.starts_with("SELECT") {
            Invalid(Some(" --< Expect: SELECT stmt".to_owned()))
        } else if !input.ends_with(';') {
            Incomplete
        } else {
            Valid(None)
        };
        Ok(result)
    }
}

fn main() -> Result<()> {
    let h = InputValidator {};
    let mut rl = Editor::new()?;
    rl.set_helper(Some(h));

    let input = rl.readline("> ")?;
    println!("Input: {input}");
    Ok(())
}