reedline/validator/
default.rs1use crate::{ValidationResult, Validator};
2
3pub struct DefaultValidator;
5
6impl Validator for DefaultValidator {
7 fn validate(&self, line: &str) -> ValidationResult {
8 if line.split('"').count() % 2 == 0 || incomplete_brackets(line) {
9 ValidationResult::Incomplete
10 } else {
11 ValidationResult::Complete
12 }
13 }
14}
15
16fn incomplete_brackets(line: &str) -> bool {
17 let mut balance: Vec<char> = Vec::new();
18
19 for c in line.chars() {
20 if c == '{' {
21 balance.push('}');
22 } else if c == '[' {
23 balance.push(']');
24 } else if c == '(' {
25 balance.push(')');
26 } else if ['}', ']', ')'].contains(&c) {
27 if let Some(last) = balance.last() {
28 if last == &c {
29 balance.pop();
30 }
31 }
32 }
33 }
34
35 !balance.is_empty()
36}
37
38#[cfg(test)]
39mod test {
40 use super::*;
41 use rstest::rstest;
42
43 #[rstest]
44 #[case("(([[]]))", false)]
45 #[case("(([[]]", true)]
46 #[case("{[}]", true)]
47 #[case("{[]}{()}", false)]
48 fn test_incomplete_brackets(#[case] input: &str, #[case] expected: bool) {
49 let result = incomplete_brackets(input);
50
51 assert_eq!(result, expected);
52 }
53}