diff options
| author | sigoden <sigoden@gmail.com> | 2023-03-12 07:54:18 +0800 |
|---|---|---|
| committer | sigoden <sigoden@gmail.com> | 2023-03-12 07:54:18 +0800 |
| commit | 0ed0ad1fd26cccb9f41379e2f0f2c77fca43c608 (patch) | |
| tree | f0e44c0fd0d62c7a8ddb3ffe77f8e5687d855b5d /src/repl/validator.rs | |
| parent | 4aab872ee1033df31827a35a1af2ee9f1ec2e2e7 (diff) | |
| download | aichat-0ed0ad1fd26cccb9f41379e2f0f2c77fca43c608.tar.gz | |
chore: optimize readline multiline
Diffstat (limited to 'src/repl/validator.rs')
| -rw-r--r-- | src/repl/validator.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/repl/validator.rs b/src/repl/validator.rs new file mode 100644 index 0000000..e1f6e99 --- /dev/null +++ b/src/repl/validator.rs @@ -0,0 +1,59 @@ +use reedline::{ValidationResult, Validator}; + +/// A default validator which checks for mismatched quotes and brackets +pub struct ReplValidator; + +impl Validator for ReplValidator { + fn validate(&self, line: &str) -> ValidationResult { + if incomplete_brackets(line) { + ValidationResult::Incomplete + } else { + ValidationResult::Complete + } + } +} + +fn incomplete_brackets(line: &str) -> bool { + let mut balance: Vec<char> = Vec::new(); + let mut symbol = None; + for c in line.chars() { + match symbol { + Some(s) => match (s, c) { + ('{', '}') | ('(', ')') => { + balance.pop(); + } + _ if s == c => { + balance.push(c); + } + _ => {} + }, + None => match c { + '{' | '(' => { + balance.push(c); + symbol = Some(c) + } + _ => {} + }, + } + } + + !balance.is_empty() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_incomplete_brackets() { + assert!(incomplete_brackets("{")); + assert!(incomplete_brackets("(")); + assert!(!incomplete_brackets("{}")); + assert!(!incomplete_brackets("()")); + assert!(!incomplete_brackets("{ab\nc}")); + assert!(!incomplete_brackets("(ab\nc)")); + assert!(!incomplete_brackets("{[}")); + assert!(!incomplete_brackets("{{{{{}}}}}")); + assert!(incomplete_brackets("{{}")); + } +} |
