pub use crate::text::WidthMode;
use crate::unicode::graphemes;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Token<'a> {
Text {
text: &'a [u8],
width: u16,
},
Escape(&'a [u8]),
Control(u8),
}
pub fn string_width(bytes: &[u8], mode: WidthMode, eaw_wide: bool) -> usize {
tokenize(bytes, mode, eaw_wide)
.filter_map(|t| match t {
Token::Text { width, .. } => Some(width as usize),
_ => None,
})
.sum()
}
pub fn tokenize(bytes: &[u8], mode: WidthMode, eaw_wide: bool) -> Tokenizer<'_> {
Tokenizer {
bytes,
pos: 0,
mode,
eaw_wide,
scan_end: 0,
run: "",
#[cfg(test)]
scanned: 0,
#[cfg(test)]
validated: 0,
}
}
pub struct Tokenizer<'a> {
bytes: &'a [u8],
pos: usize,
mode: WidthMode,
eaw_wide: bool,
scan_end: usize,
run: &'a str,
#[cfg(test)]
scanned: usize,
#[cfg(test)]
validated: usize,
}
impl<'a> Tokenizer<'a> {
#[inline]
fn validate(&mut self, to: usize) {
let from = self.pos;
#[cfg(test)]
{
self.validated += to - from;
}
self.run = std::str::from_utf8(&self.bytes[from..to]).unwrap_or("");
}
}
impl<'a> Iterator for Tokenizer<'a> {
type Item = Token<'a>;
fn next(&mut self) -> Option<Token<'a>> {
let b = *self.bytes.get(self.pos)?;
if (0x20..0x7f).contains(&b) && self.bytes.get(self.pos + 1).is_none_or(u8::is_ascii) {
let start = self.pos;
self.pos += 1;
if !self.run.is_empty() {
self.run = &self.run[1..];
}
return Some(Token::Text {
text: &self.bytes[start..self.pos],
width: 1,
});
}
if b == 0x1b || is_c1_introducer(b) {
let start = self.pos;
let end = scan_sequence(self.bytes, start);
self.pos = end;
return Some(Token::Escape(&self.bytes[start..end]));
}
if self.run.is_empty() {
if b < 0x20 || b == 0x7f || (0x80..=0x9f).contains(&b) {
self.pos += 1;
return Some(Token::Control(b));
}
if self.pos >= self.scan_end {
let mut end = self.pos;
while end < self.bytes.len() {
let bb = self.bytes[end];
if bb == 0x1b || bb < 0x20 || bb == 0x7f || (0x80..=0x9f).contains(&bb) {
break;
}
match utf8_char_at(self.bytes, end) {
Some(n) => end += n,
None => break,
}
}
#[cfg(test)]
{
self.scanned += end.max(self.pos + 1) - self.pos;
}
self.scan_end = end;
self.validate(end);
}
if self.run.is_empty() {
self.pos += 1;
return Some(Token::Control(b));
}
}
let g = graphemes(self.run).next()?;
let start = self.pos;
self.pos += g.len();
self.run = &self.run[g.len()..];
let width = self.mode.grapheme_width(g, self.eaw_wide) as u16;
Some(Token::Text {
text: &self.bytes[start..self.pos],
width,
})
}
}
fn utf8_char_at(bytes: &[u8], i: usize) -> Option<usize> {
let n = utf8_char_len(bytes[i]);
if n == 0 || i + n > bytes.len() {
return None;
}
if n > 1 && std::str::from_utf8(&bytes[i..i + n]).is_err() {
return None;
}
Some(n)
}
#[inline]
fn utf8_char_len(b: u8) -> usize {
match b {
0x00..=0x7f => 1,
0xc2..=0xdf => 2,
0xe0..=0xef => 3,
0xf0..=0xf4 => 4,
_ => 0,
}
}
#[inline]
fn is_c1_introducer(b: u8) -> bool {
matches!(b, 0x90 | 0x98 | 0x9b | 0x9d | 0x9e | 0x9f)
}
fn scan_sequence(bytes: &[u8], start: usize) -> usize {
let len = bytes.len();
let head = bytes[start];
match head {
0x1b => {
let i = start + 1;
if i >= len {
return len;
}
match bytes[i] {
b'[' => scan_csi(bytes, i + 1),
b']' => scan_string(bytes, i + 1, true),
b'P' | b'X' | b'^' | b'_' => scan_string(bytes, i + 1, false),
_ => scan_esc_intermediate(bytes, i),
}
}
0x9b => scan_csi(bytes, start + 1),
0x9d => scan_string(bytes, start + 1, true),
0x90 | 0x98 | 0x9e | 0x9f => scan_string(bytes, start + 1, false),
_ => start + 1,
}
}
fn scan_csi(bytes: &[u8], from: usize) -> usize {
let len = bytes.len();
let mut i = from;
while i < len {
if (0x40..=0x7e).contains(&bytes[i]) {
return i + 1;
}
i += 1;
}
len
}
fn scan_string(bytes: &[u8], from: usize, bel_ends: bool) -> usize {
let len = bytes.len();
let mut i = from;
while i < len {
let b = bytes[i];
if b == 0x9c || (b == 0x07 && bel_ends) {
return i + 1;
}
if b == 0x1b && i + 1 < len && bytes[i + 1] == b'\\' {
return i + 2;
}
if b == 0x1b {
return i;
}
i += utf8_char_at(bytes, i).unwrap_or(1);
}
len
}
fn scan_esc_intermediate(bytes: &[u8], at: usize) -> usize {
let len = bytes.len();
let mut i = at;
while i < len && (0x20..=0x2f).contains(&bytes[i]) {
i += 1;
}
if i < len {
i + utf8_char_at(bytes, i).unwrap_or(1)
} else {
len
}
}
#[cfg(test)]
mod util {
use super::*;
pub(super) fn tokens(input: &[u8]) -> Vec<Token<'_>> {
tokenize(input, WidthMode::Grapheme, false).collect()
}
pub(super) fn visible(toks: &[Token<'_>]) -> String {
toks.iter()
.filter_map(|t| match t {
Token::Text { text, .. } => {
Some(std::str::from_utf8(text).expect("a text token is whole UTF-8"))
}
_ => None,
})
.collect()
}
pub(super) fn rebuild(toks: &[Token<'_>]) -> Vec<u8> {
let mut out = Vec::new();
for t in toks {
match t {
Token::Text { text, .. } | Token::Escape(text) => out.extend_from_slice(text),
Token::Control(c) => out.push(*c),
}
}
out
}
pub(super) fn forms(seven: &[u8], eight: u8) -> [(&'static str, Vec<u8>); 2] {
[("7-bit", seven.to_vec()), ("8-bit", vec![eight])]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokenize_plain_text() {
let toks: Vec<_> = tokenize(b"abc", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 3);
assert!(matches!(
toks[0],
Token::Text {
text: b"a",
width: 1
}
));
}
#[test]
fn tokenize_csi() {
let toks: Vec<_> = tokenize(b"\x1b[31mhi\x1b[m", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 4);
assert!(matches!(toks[0], Token::Escape(b"\x1b[31m")));
assert!(matches!(toks[3], Token::Escape(b"\x1b[m")));
}
#[test]
fn tokenize_osc_bel() {
let toks: Vec<_> = tokenize(b"\x1b]0;title\x07rest", WidthMode::Grapheme, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x1b]0;title\x07")));
}
#[test]
fn tokenize_osc_st() {
let toks: Vec<_> =
tokenize(b"\x1b]0;title\x1b\\rest", WidthMode::Grapheme, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x1b]0;title\x1b\\")));
}
#[test]
fn tokenize_wide_char() {
let toks: Vec<_> = tokenize("ä¸".as_bytes(), WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 1);
assert!(matches!(toks[0], Token::Text { width: 2, .. }));
}
#[test]
fn tokenize_newline_control() {
let toks: Vec<_> = tokenize(b"a\nb", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 3);
assert!(matches!(toks[1], Token::Control(b'\n')));
}
#[test]
fn string_width_ignores_escapes() {
assert_eq!(
string_width(b"\x1b[31mhello\x1b[m", WidthMode::Grapheme, false),
5
);
assert_eq!(
string_width("䏿–‡".as_bytes(), WidthMode::Grapheme, false),
4
);
}
#[test]
fn tokenize_8bit_csi() {
let toks: Vec<_> = tokenize(b"\x9b31mhi\x9bm", WidthMode::Grapheme, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x9b31m")));
assert!(matches!(toks[3], Token::Escape(b"\x9bm")));
}
#[test]
fn tokenize_8bit_osc_with_8bit_st() {
let toks: Vec<_> = tokenize(b"\x9d0;title\x9crest", WidthMode::Grapheme, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x9d0;title\x9c")));
assert_eq!(toks.len(), 5);
}
#[test]
fn tokenize_8bit_dcs() {
let toks: Vec<_> = tokenize(b"\x90q!data\x9cafter", WidthMode::Grapheme, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x90q!data\x9c")));
}
#[test]
fn tokenize_8bit_sos_pm_apc() {
for &intro in &[0x98u8, 0x9e, 0x9f] {
let mut input = vec![intro];
input.extend_from_slice(b"payload");
input.push(0x9c);
let toks: Vec<_> = tokenize(&input, WidthMode::Grapheme, false).collect();
match toks[0] {
Token::Escape(esc) => {
assert_eq!(esc[0], intro);
assert_eq!(*esc.last().unwrap(), 0x9c);
}
ref other => panic!("expected Escape for 0x{intro:02x}, got {other:?}"),
}
}
}
#[test]
fn tokenize_standalone_c1_is_control() {
let toks: Vec<_> = tokenize(b"a\x84b", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 3);
assert!(matches!(toks[1], Token::Control(0x84)));
}
#[test]
fn tokenize_8bit_st_outside_string_is_control() {
let toks: Vec<_> = tokenize(b"\x9c", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 1);
assert!(matches!(toks[0], Token::Control(0x9c)));
}
#[test]
fn tokenize_two_byte_esc() {
let toks: Vec<_> = tokenize(b"a\x1b=b", WidthMode::Grapheme, false).collect();
assert_eq!(toks.len(), 3);
assert!(matches!(toks[1], Token::Escape(b"\x1b=")));
}
}
#[cfg(test)]
mod sequences {
use super::util::*;
use super::*;
const STRINGS: &[(&str, &[u8], u8)] = &[
("OSC", b"\x1b]", 0x9d),
("DCS", b"\x1bP", 0x90),
("SOS", b"\x1bX", 0x98),
("PM", b"\x1b^", 0x9e),
("APC", b"\x1b_", 0x9f),
];
const TERMINATORS: &[(&str, &[u8])] = &[
("BEL", b"\x07"),
("ESC backslash", b"\x1b\\"),
("8-bit ST", b"\x9c"),
];
const PAYLOADS: &[(&str, &str)] = &[
("ascii", "0;plain title"),
("utf8", "0;caf\u{e9} \u{2705} \u{4e00} \u{1f600}"),
];
#[test]
fn every_string_sequence_is_one_whole_token() {
for (name, seven, eight) in STRINGS {
for (pname, payload) in PAYLOADS {
for (tname, term) in TERMINATORS {
if *term == b"\x07" && *name != "OSC" {
continue;
}
for (form, intro) in forms(seven, *eight) {
let mut input = intro;
input.extend_from_slice(payload.as_bytes());
input.extend_from_slice(term);
let seq_len = input.len();
input.extend_from_slice("after \u{2705}".as_bytes());
let what = format!("{name} {form} {pname} payload, {tname} terminator");
let toks = tokens(&input);
assert_eq!(
toks.first(),
Some(&Token::Escape(&input[..seq_len])),
"{what}: the sequence is not one token"
);
assert_eq!(
visible(&toks[1..]),
"after \u{2705}",
"{what}: text after was lost"
);
assert_eq!(
string_width(&input, WidthMode::Grapheme, false),
8,
"{what}: the sequence was measured"
);
}
}
}
}
}
#[test]
fn an_unterminated_string_sequence_runs_to_the_end() {
for (name, seven, eight) in STRINGS {
for (form, intro) in forms(seven, *eight) {
for (pname, payload) in PAYLOADS {
let mut input = intro.clone();
input.extend_from_slice(payload.as_bytes());
let toks = tokens(&input);
assert_eq!(
toks,
vec![Token::Escape(&input[..])],
"{name} {form} {pname}: an unterminated sequence should be one token"
);
assert_eq!(string_width(&input, WidthMode::Grapheme, false), 0);
}
}
}
}
#[test]
fn a_lone_esc_ends_a_string_and_is_reparsed() {
for (name, seven, eight) in STRINGS {
for (form, intro) in forms(seven, *eight) {
let mut input = intro.clone();
input.extend_from_slice("pay\u{2705}".as_bytes());
let cut = input.len();
input.extend_from_slice(b"\x1b[31mZ");
let toks = tokens(&input);
assert_eq!(
toks[0],
Token::Escape(&input[..cut]),
"{name} {form}: the string should stop at the ESC"
);
assert_eq!(
toks[1],
Token::Escape(b"\x1b[31m"),
"{name} {form}: the CSI after it should survive whole"
);
assert_eq!(
toks[2],
Token::Text {
text: b"Z",
width: 1
}
);
}
}
}
#[test]
fn adjacent_sequences_do_not_merge() {
let cases: &[(&[u8], &[u8], &[u8])] = &[
(
b"\x1b]0;a\x07\x1bPq\x1b\\Z",
b"\x1b]0;a\x07",
b"\x1bPq\x1b\\",
),
(b"\x9fa\x9c\x9eb\x9cZ", b"\x9fa\x9c", b"\x9eb\x9c"),
(b"\x9d0;a\x1b\\\x1b^b\x9cZ", b"\x9d0;a\x1b\\", b"\x1b^b\x9c"),
];
for (input, first, second) in cases {
let toks = tokens(input);
assert_eq!(toks[0], Token::Escape(first), "{input:x?}");
assert_eq!(toks[1], Token::Escape(second), "{input:x?}");
assert_eq!(
toks[2],
Token::Text {
text: b"Z",
width: 1
},
"{input:x?}"
);
}
}
#[test]
fn real_payloads_survive() {
let cases: &[(&str, &[u8], &[u8], &str)] = &[
(
"sixel",
b"\x1bPq#0;2;0;0;0#1;2;100;100;100\x1b\\ok",
b"\x1bPq#0;2;0;0;0#1;2;100;100;100\x1b\\",
"ok",
),
(
"DECRQSS reply",
b"\x1bP1$r0;1m\x1b\\ok",
b"\x1bP1$r0;1m\x1b\\",
"ok",
),
(
"OSC 8 hyperlink with a UTF-8 target",
b"\x1b]8;;https://example.com/\xe2\x9c\x85\x07link\x1b]8;;\x07",
b"\x1b]8;;https://example.com/\xe2\x9c\x85\x07",
"link",
),
(
"OSC with an empty payload",
b"\x1b]\x07ok",
b"\x1b]\x07",
"ok",
),
(
"8-bit APC with an empty payload",
b"\x9f\x9cok",
b"\x9f\x9c",
"ok",
),
];
for (what, input, opening, want) in cases {
let toks = tokens(input);
assert_eq!(toks.first(), Some(&Token::Escape(opening)), "{what}");
assert_eq!(visible(&toks), *want, "{what}");
assert_eq!(
rebuild(&toks),
*input,
"{what}: the stream did not reassemble"
);
}
}
#[test]
fn a_c1_byte_inside_a_character_is_not_a_control() {
let toks = tokens(b"\x1b]0;title\x9cZ");
assert_eq!(toks[0], Token::Escape(b"\x1b]0;title\x9c"));
assert_eq!(
toks[1],
Token::Text {
text: b"Z",
width: 1
}
);
let unterminated = b"\x1b]0;title\xc2\x9cZ";
assert_eq!(tokens(unterminated), vec![Token::Escape(&unterminated[..])]);
let toks = tokens(b"\x9d0;title\x07Z");
assert_eq!(toks[0], Token::Escape(b"\x9d0;title\x07"));
let toks = tokens(b"\xc2\x9d0;title\x07Z");
assert!(
!matches!(toks[0], Token::Escape(_)),
"the character U+009D opened a sequence: {toks:?}"
);
assert_eq!(
string_width(b"\xc2\x9d0;title\x07Z", WidthMode::Wc, false),
8
);
let toks = tokens(b"\x1b]0;\xe2\x9c\x85\x07Z");
assert_eq!(toks[0], Token::Escape(b"\x1b]0;\xe2\x9c\x85\x07"));
}
#[test]
fn bel_ends_an_osc_and_nothing_else() {
for (name, seven, eight) in STRINGS {
for (form, intro) in forms(seven, *eight) {
let mut input = intro;
input.extend_from_slice(b"pay\x07load");
let bel_at = input.len() - b"load".len();
input.extend_from_slice(b"\x9cZ");
let toks = tokens(&input);
let what = format!("{name} {form}");
if *name == "OSC" {
assert_eq!(
toks[0],
Token::Escape(&input[..bel_at]),
"{what}: BEL should have ended it"
);
assert!(
toks.iter()
.any(|t| matches!(t, Token::Text { text: b"l", .. })),
"{what}: text after the BEL went missing"
);
} else {
assert_eq!(
toks[0],
Token::Escape(&input[..input.len() - 1]),
"{what}: BEL is payload, so it should have run to the ST"
);
assert_eq!(
toks[1],
Token::Text {
text: b"Z",
width: 1
},
"{what}"
);
assert_eq!(string_width(&input, WidthMode::Grapheme, false), 1);
}
}
}
}
#[test]
fn every_c1_byte_depends_on_the_decoder_state() {
for c in 0x80u8..=0x9f {
let single = [c];
let alone: Vec<Token<'_>> = tokenize(&single, WidthMode::Wc, false).collect();
match alone.as_slice() {
[Token::Control(got)] => assert_eq!(*got, c),
[Token::Escape(seq)] => assert!(
is_c1_introducer(c) && *seq == &single[..],
"0x{c:02x} opened a sequence but is not an introducer"
),
other => panic!("0x{c:02x} alone produced {other:?}"),
}
assert_eq!(string_width(&single, WidthMode::Wc, false), 0);
let encoded = [0xc2, c];
let inside: Vec<Token<'_>> = tokenize(&encoded, WidthMode::Wc, false).collect();
assert_eq!(
inside,
vec![Token::Text {
text: &encoded[..],
width: 0
}],
"U+{:04X} was not read as a character",
0x80 + u32::from(c) - 0x80
);
let mut raw = b"\x1b]0;".to_vec();
raw.push(c);
raw.extend_from_slice(b"Z\x07");
let ends_early = matches!(
tokenize(&raw, WidthMode::Wc, false).next(),
Some(Token::Escape(seq)) if seq.len() < raw.len()
);
assert_eq!(
ends_early,
c == 0x9c || c == 0x1b,
"0x{c:02x} in a payload terminated the sequence unexpectedly"
);
let mut encoded_in = b"\x1b]0;".to_vec();
encoded_in.extend_from_slice(&encoded);
encoded_in.extend_from_slice(b"Z\x07");
let len = encoded_in.len();
assert_eq!(
tokenize(&encoded_in, WidthMode::Wc, false).next(),
Some(Token::Escape(&encoded_in[..len])),
"U+00{c:02X} in a payload ended the sequence"
);
}
}
}
#[cfg(test)]
mod fast_path {
use super::util::*;
use super::*;
#[test]
fn cached_runs_stop_before_controls_escapes_and_invalid_bytes() {
let before = "abä¸e\u{301}".as_bytes();
let after = "xy界".as_bytes();
for boundary in [
&b"\n"[..],
b"\x7f",
b"\x9c",
b"\xff",
b"\x1b[31m",
b"\x9b31m",
b"\x1b]0;title\x07",
b"\x1bPpayload\x1b\\",
] {
let input = [before, boundary, after].concat();
for mode in [WidthMode::Wc, WidthMode::Grapheme] {
for eaw_wide in [false, true] {
let expected: Vec<_> = [before, boundary, after]
.into_iter()
.flat_map(|part| tokenize(part, mode, eaw_wide))
.collect();
let mut iter = tokenize(&input, mode, eaw_wide);
assert_eq!(iter.by_ref().collect::<Vec<_>>(), expected);
assert_eq!(iter.next(), None);
}
}
}
}
fn text_tokens_eaw(s: &str, mode: WidthMode, eaw_wide: bool) -> Vec<(String, u16)> {
tokenize(s.as_bytes(), mode, eaw_wide)
.filter_map(|t| match t {
Token::Text { text, width } => Some((
std::str::from_utf8(text)
.expect("a text token is whole UTF-8")
.to_owned(),
width,
)),
_ => None,
})
.collect()
}
#[test]
fn the_ascii_shortcut_agrees_with_grapheme_segmentation() {
for mode in [WidthMode::Wc, WidthMode::Grapheme] {
for eaw_wide in [false, true] {
let toks = |s: &str| text_tokens_eaw(s, mode, eaw_wide);
assert_eq!(
toks("abc"),
vec![("a".into(), 1), ("b".into(), 1), ("c".into(), 1)],
"plain ASCII is one column per byte"
);
assert_eq!(
toks("e\u{301}f"),
vec![("e\u{301}".into(), 1), ("f".into(), 1)],
"a combining mark still joins the ASCII base before it"
);
assert_eq!(
toks("a"),
vec![("a".into(), 1)],
"the last byte of the input takes the shortcut too"
);
assert_eq!(
toks("1\u{fe0f}\u{20e3}z"),
vec![("1\u{fe0f}\u{20e3}".into(), 1), ("z".into(), 1)],
"a keycap keeps its ASCII digit"
);
assert_eq!(
toks("a\u{200d}b"),
vec![("a\u{200d}".into(), 1), ("b".into(), 1)],
"a ZWJ joins the ASCII base before it"
);
assert_eq!(
toks("a\u{4e00}b"),
vec![("a".into(), 1), ("\u{4e00}".into(), 2), ("b".into(), 1)],
"a wide character between two ASCII ones is still wide"
);
}
}
assert_eq!(
text_tokens_eaw("a\u{2018}b", WidthMode::Wc, false),
vec![("a".into(), 1), ("\u{2018}".into(), 1), ("b".into(), 1)]
);
assert_eq!(
text_tokens_eaw("a\u{2018}b", WidthMode::Wc, true),
vec![("a".into(), 1), ("\u{2018}".into(), 2), ("b".into(), 1)]
);
}
#[test]
fn controls_never_reach_the_ascii_shortcut() {
for b in 0u8..=0x7f {
let input = [b];
let toks: Vec<_> = tokenize(&input, WidthMode::Wc, false).collect();
match toks.as_slice() {
[Token::Text { text, width }] => {
assert!(
(0x20..=0x7e).contains(&b),
"0x{b:02x} was emitted as text, but only printable ASCII may be"
);
assert_eq!(*text, &input[..]);
assert_eq!(*width, 1);
}
[Token::Control(c)] => {
assert_eq!(*c, b);
assert!(
b < 0x20 || b == 0x7f,
"0x{b:02x} is printable but was emitted as a control"
);
}
[Token::Escape(seq)] => assert_eq!(*seq, b"\x1b"),
other => panic!("0x{b:02x} produced {other:?}"),
}
}
}
#[test]
fn a_continuation_byte_does_not_terminate_a_string_sequence() {
const PREFIXES: &[&[u8]] = &[
b"\x1b]0;", b"\x1bP", b"\x1b_", b"\x1b^", b"\x1bX", b"\x1b", b"\x1b ", b"\x1b#",
];
for c in [
'\u{2705}',
'\u{2714}',
'\u{2728}',
'\u{171c}',
'\u{4e00}',
'\u{1f600}',
] {
for prefix in PREFIXES {
let mut input = prefix.to_vec();
input.extend_from_slice(c.to_string().as_bytes());
input.extend_from_slice(b"\x07after");
for t in tokenize(&input, WidthMode::Wc, false) {
let bytes = match t {
Token::Text { text, .. } | Token::Escape(text) => text,
Token::Control(_) => continue,
};
assert!(
std::str::from_utf8(bytes).is_ok(),
"{input:x?} produced a token split mid-character: {bytes:x?}"
);
}
}
}
for c in ['\u{2705}', '\u{2714}', '\u{2728}', '\u{171c}'] {
let mut input = b"\x1b]0;Build ".to_vec();
input.extend_from_slice(c.to_string().as_bytes());
input.extend_from_slice(b"\x07after");
let toks: Vec<_> = tokenize(&input, WidthMode::Wc, false).collect();
let (escape, rest) = toks.split_first().expect("a token");
let Token::Escape(seq) = escape else {
panic!("expected the OSC to be one escape token, got {escape:?}")
};
let mut want = b"\x1b]0;Build ".to_vec();
want.extend_from_slice(c.to_string().as_bytes());
want.push(0x07);
assert_eq!(*seq, &want[..], "the sequence is whole");
assert_eq!(visible(rest), "after");
}
let toks: Vec<_> = tokenize(b"\x1b\xe2\x9c\x85x", WidthMode::Wc, false).collect();
assert_eq!(toks[0], Token::Escape(b"\x1b\xe2\x9c\x85"));
let toks: Vec<_> = tokenize(b"\x1b]0;t\x9cx", WidthMode::Wc, false).collect();
assert!(matches!(toks[0], Token::Escape(b"\x1b]0;t\x9c")));
}
#[test]
fn a_malformed_byte_does_not_swallow_a_terminator() {
let cases: &[(&[u8], &[u8])] = &[
(b"\x1b]0;\xe0\x07Zz", b"\x1b]0;\xe0\x07"),
(b"\x1b]0;\xf0\x1b\\Zz", b"\x1b]0;\xf0\x1b\\"),
(b"\x1b]0;\xe0\x9cZz", b"\x1b]0;\xe0\x9c"),
(b"\x1b_G\xf0\x9f\x1b\\Zz", b"\x1b_G\xf0\x9f\x1b\\"),
(b"\x1b]0;\xc2\x07visible", b"\x1b]0;\xc2\x07"),
];
for (input, escape) in cases {
let toks: Vec<_> = tokenize(input, WidthMode::Wc, false).collect();
assert_eq!(
toks.first(),
Some(&Token::Escape(escape)),
"input {input:x?} did not stop at its terminator"
);
assert!(
!visible(&toks).is_empty(),
"input {input:x?} lost all its text"
);
}
let toks: Vec<_> = tokenize(b"\x1b\xe0\x1b[31mZ", WidthMode::Wc, false).collect();
assert_eq!(toks[0], Token::Escape(b"\x1b\xe0"));
assert_eq!(toks[1], Token::Escape(b"\x1b[31m"));
}
#[test]
fn arbitrary_bytes_never_panic_or_split_a_character() {
let pinned: &[(&[u8], &str)] = &[
(
b"\xe0\x20\x0d\xef\xb8\x8f",
"Ce0 T[20]w1 C0d T[ef, b8, 8f]w0",
),
(
b"\xf0\x30\x0d\x5b\xe2\x9c\x85\x30",
"Cf0 T[30]w1 C0d T[5b]w1 T[e2, 9c, 85]w2 T[30]w1",
),
(
b"\xe0\x41\x1b\x41\xc3\xa9",
"Ce0 T[41]w1 E[1b, 41] T[c3, a9]w1",
),
(b"\xcf\xc8\x9c", "Ccf T[c8, 9c]w1"),
(
b"\xe3\x61\x0a\xc4\x81\xc4\x81\x78",
"Ce3 T[61]w1 C0a T[c4, 81]w1 T[c4, 81]w1 T[78]w1",
),
];
for (seed, expected) in pinned {
let rendered: Vec<String> = tokenize(seed, WidthMode::Grapheme, false)
.map(|t| match t {
Token::Text { text, width } => format!("T{text:x?}w{width}"),
Token::Escape(b) => format!("E{b:x?}"),
Token::Control(c) => format!("C{c:02x}"),
})
.collect();
assert_eq!(rendered.join(" "), *expected, "input {seed:x?}");
string_width(seed, WidthMode::Grapheme, false);
string_width(seed, WidthMode::Wc, false);
}
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut buf = [0u8; 24];
for _ in 0..200_000 {
let len = {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % 24) as usize
};
for b in buf.iter_mut().take(len) {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
*b =
match state % 4 {
0 => (state >> 8) as u8,
1 => [0x1b, 0x9b, 0x9d, 0x90, 0x98, 0x9e, 0x9f, 0x07]
[(state >> 8) as usize % 8],
2 => [0xc2, 0xe0, 0xe2, 0xf0, 0xf4, 0xff, 0x9c, 0x80]
[(state >> 8) as usize % 8],
_ => b"abc \n\r\\;0"[(state >> 8) as usize % 9],
};
}
let input = &buf[..len];
for t in tokenize(input, WidthMode::Grapheme, false) {
if let Token::Text { text, .. } = t {
assert!(
std::str::from_utf8(text).is_ok(),
"{input:x?} produced a split character {text:x?}"
);
}
}
string_width(input, WidthMode::Grapheme, false);
}
}
}
#[cfg(test)]
mod scaling {
use super::util::*;
use super::*;
fn scan_cost(bytes: &[u8]) -> (usize, usize) {
let mut t = tokenize(bytes, WidthMode::Wc, false);
let toks: Vec<_> = (&mut t).collect();
let _ = visible(&toks);
assert_eq!(rebuild(&toks), bytes, "tokens did not reassemble the input");
(t.scanned, t.validated)
}
#[test]
fn tokenizing_one_long_line_is_linear_in_its_length() {
for n in [1_000usize, 4_000, 16_000, 64_000] {
let line: String = std::iter::repeat_n('x', n).collect();
assert_eq!(
scan_cost(line.as_bytes()),
(0, 0),
"printable ASCII needs neither a run scan nor UTF-8 validation"
);
}
}
#[test]
fn tokenizing_a_long_non_ascii_line_is_linear_too() {
for unit in ["\u{e9}", "\u{4e00}", "\u{1f600}", "e\u{301}"] {
for n in [1_000usize, 4_000, 16_000, 64_000] {
let line = unit.repeat(n);
let len = line.len();
assert_eq!(
scan_cost(line.as_bytes()),
(len, len),
"{unit:?} x{n}: the run is found once and validated once"
);
}
}
}
#[test]
fn malformed_utf8_is_linear_too() {
for n in [1_000usize, 4_000, 16_000, 64_000] {
let bytes: Vec<u8> = std::iter::repeat_n([0xc2u8, 0x41], n / 2)
.flatten()
.collect();
let (scanned, validated) = scan_cost(&bytes);
assert!(
scanned <= 2 * n,
"scanning {n} malformed bytes visited {scanned} of them"
);
assert!(
validated <= 2 * n,
"validating {n} malformed bytes submitted {validated} of them"
);
}
}
}