use super::error::Error;
use super::storage::{Tape, TapeStorage};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Standard,
Lines,
}
struct RawStructure {
offsets: Vec<i32>,
pairs: Vec<(usize, usize)>,
}
fn scan_structural(bytes: &[u8], base: usize, mark_newline: bool) -> Result<RawStructure, Error> {
let mut offsets = Vec::new();
let mut pairs = Vec::new();
let mut stack: Vec<(u8, usize)> = Vec::new();
let mut in_string = false;
let mut escape = false;
for (i, &b) in bytes.iter().enumerate() {
if in_string {
if escape {
escape = false;
} else if b == b'\\' {
escape = true;
} else if b == b'"' {
in_string = false;
}
continue;
}
match b {
b'"' => in_string = true,
b'{' | b'[' => {
offsets.push((base + i + 1) as i32);
stack.push((b, offsets.len() - 1));
}
b'}' | b']' => {
offsets.push((base + i + 1) as i32);
let (open_b, open_idx) = stack.pop().ok_or(Error::UnbalancedBrackets)?;
let expected = if b == b'}' { b'{' } else { b'[' };
if open_b != expected {
return Err(Error::UnbalancedBrackets);
}
pairs.push((open_idx, offsets.len() - 1));
}
b':' | b',' => {
offsets.push((base + i + 1) as i32);
}
b'\n' if mark_newline => {
offsets.push((base + i + 1) as i32);
}
_ => {}
}
}
if in_string {
return Err(Error::UnterminatedString);
}
if !stack.is_empty() {
return Err(Error::UnbalancedBrackets);
}
Ok(RawStructure { offsets, pairs })
}
fn build_lines(input: &[u8]) -> Result<RawStructure, Error> {
scan_structural(input, 0, true)
}
pub fn build_tape_cpu(input: &[u8], mode: Mode) -> Result<Tape, Error> {
if input.is_empty() {
return Err(Error::EmptyInput);
}
std::str::from_utf8(input).map_err(|_| Error::InvalidUtf8)?;
let RawStructure { offsets, pairs } = match mode {
Mode::Standard => scan_structural(input, 0, false)?,
Mode::Lines => build_lines(input)?,
};
let n = offsets.len();
let total = n + 2;
let mut structural = vec![0i32; total];
structural[1..=n].copy_from_slice(&offsets);
structural[n + 1] = (n + 1) as i32;
let mut pair_pos = vec![-1i32; total];
pair_pos[0] = (n + 1) as i32; pair_pos[n + 1] = 0; for (a, b) in pairs {
pair_pos[a + 1] = (b + 1) as i32;
}
Ok(Tape {
structural: TapeStorage::from(structural),
pair_pos: TapeStorage::from(pair_pos),
})
}