#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Cat {
Escape = 0,
BeginGroup = 1,
EndGroup = 2,
MathShift = 3,
AlignTab = 4,
EndLine = 5,
Param = 6,
Superscript = 7,
Subscript = 8,
Ignored = 9,
Space = 10,
Letter = 11,
Other = 12,
Active = 13,
Comment = 14,
Invalid = 15,
}
pub struct CatTable {
codes: [Cat; 256],
generation: u32,
}
impl Default for CatTable {
fn default() -> Self {
Self::new()
}
}
impl CatTable {
pub fn new() -> Self {
let mut codes = [Cat::Other; 256];
for c in b'A'..=b'Z' {
codes[c as usize] = Cat::Letter;
}
for c in b'a'..=b'z' {
codes[c as usize] = Cat::Letter;
}
codes[b'\\' as usize] = Cat::Escape;
codes[b'%' as usize] = Cat::Comment;
codes[b'\r' as usize] = Cat::EndLine;
codes[b'\n' as usize] = Cat::EndLine;
codes[b' ' as usize] = Cat::Space;
codes[0] = Cat::Ignored;
codes[127] = Cat::Invalid;
Self {
codes,
generation: 0,
}
}
pub fn generation(&self) -> u32 {
self.generation
}
pub fn get(&self, c: char) -> Cat {
match u32::from(c) {
n if n > 255 => Cat::Letter,
n => self.codes[n as usize],
}
}
pub fn set(&mut self, c: char, cat: Cat) {
if let Ok(i) = usize::try_from(u32::from(c)) {
if i < 256 {
self.codes[i] = cat;
self.generation = self.generation.wrapping_add(1);
}
}
}
}
pub fn cat_from_i64(n: i64) -> Option<Cat> {
Some(match n {
0 => Cat::Escape,
1 => Cat::BeginGroup,
2 => Cat::EndGroup,
3 => Cat::MathShift,
4 => Cat::AlignTab,
5 => Cat::EndLine,
6 => Cat::Param,
7 => Cat::Superscript,
8 => Cat::Subscript,
9 => Cat::Ignored,
10 => Cat::Space,
11 => Cat::Letter,
12 => Cat::Other,
13 => Cat::Active,
14 => Cat::Comment,
15 => Cat::Invalid,
_ => return None,
})
}