streaming_json_completer/
lib.rs

1use std::error::Error;
2use std::fmt;
3
4#[derive(Debug, Clone)]
5pub struct MalformedJsonError;
6
7impl fmt::Display for MalformedJsonError {
8    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9        write!(f, "The input JSON string is malformed.")
10    }
11}
12
13impl Error for MalformedJsonError {}
14
15pub fn complete_json(input: &str) -> Result<String, MalformedJsonError> {
16    let mut stack = Vec::new();
17    let mut in_string = false;
18    let mut escape = false;
19
20    for c in input.chars() {
21        if in_string {
22            if escape {
23                escape = false;
24            } else if c == '\\' {
25                escape = true;
26            } else if c == '"' {
27                in_string = false;
28            }
29        } else {
30            match c {
31                '{' => stack.push('}'),
32                '[' => stack.push(']'),
33                '"' => in_string = true,
34                '}' | ']' => {
35                    if stack.is_empty() {
36                        return Err(MalformedJsonError);
37                    }
38                    let last = stack.pop().unwrap();
39                    if (c == '}' && last != '}') || (c == ']' && last != ']') {
40                        return Err(MalformedJsonError);
41                    }
42                }
43                _ => (),
44            }
45        }
46    }
47
48    if in_string {
49        stack.push('"');
50    }
51
52    Ok(stack.into_iter().rev().collect())
53}