#![deny(missing_docs)]
#[derive(Debug, Default, Clone)]
pub struct Balancer {
depth: i32,
started: bool,
in_string: bool,
escape: bool,
bytes_consumed: u64,
}
impl Balancer {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, bytes: &[u8]) {
for &b in bytes {
self.bytes_consumed += 1;
if self.in_string {
if self.escape {
self.escape = false;
} else if b == b'\\' {
self.escape = true;
} else if b == b'"' {
self.in_string = false;
}
continue;
}
match b {
b'{' | b'[' => {
self.depth += 1;
self.started = true;
}
b'}' | b']' => {
if self.depth > 0 {
self.depth -= 1;
}
}
b'"' => {
self.in_string = true;
self.started = true;
}
b' ' | b'\t' | b'\n' | b'\r' => {}
_ => {
self.started = true;
}
}
}
}
pub fn complete(&self) -> bool {
self.started && self.depth == 0 && !self.in_string
}
pub fn depth(&self) -> i32 {
self.depth
}
pub fn bytes_consumed(&self) -> u64 {
self.bytes_consumed
}
pub fn reset(&mut self) {
*self = Self::new();
}
}