use super::{WidthMethod, cells, first_cluster};
static TABLE: [u8; 3840] = include!("../parser_table.in");
const GROUND: u8 = 0;
const UTF8: u8 = 14;
const PRINT: u8 = 9;
pub(super) fn string_width(text: &str, method: WidthMethod) -> usize {
let bytes = text.as_bytes();
let (mut at, mut state, mut width) = (0, GROUND, 0);
while let Some(&byte) = bytes.get(at) {
let entry = TABLE[usize::from(state) << 8 | usize::from(byte)];
state = entry & 0x0F;
if entry >> 4 == PRINT || state == UTF8 {
let (len, cells) = measure(&text[at..], method);
width += cells;
at += len;
state = GROUND;
} else {
at += 1;
}
}
width
}
fn measure(s: &str, method: WidthMethod) -> (usize, usize) {
if let (WidthMethod::WcWidth, Some(c)) = (method, s.chars().next()) {
return (c.len_utf8(), cells::wc_char(c));
}
let (cluster, width) = first_cluster(s, method);
(cluster.len().max(1), width)
}