src/adapter/strip.rs
src/adapter/strip.rs, line 136-156
let printable = unsafe {
from_utf8_unchecked(
printable,
"`bytes` was validated as UTF-8, the parser preserves UTF-8 continuations",
)
};
Some(printable)
}
}
#[inline]
unsafe fn from_utf8_unchecked<'b>(bytes: &'b [u8], safety_justification: &'static str) -> &'b str {
unsafe {
if cfg!(debug_assertions) {
// Catch problems more quickly when testing
std::str::from_utf8(bytes).expect(safety_justification)
} else {
std::str::from_utf8_unchecked(bytes)
}
}
}
The single unsafe site in the crate is from_utf8_unchecked in src/adapter/strip.rs (lines 136-156). The function wraps std::str::from_utf8_unchecked and is only called after the parser has confirmed that the byte slice contains valid UTF-8 printable characters plus UTF-8 continuation bytes. The safety justification string is passed as a &'static str parameter and is checked via str::from_utf8 under debug assertions, making any violation visible in test runs. The invariant holds: input to this crate is always &str, which guarantees UTF-8 at the call site (next_str starts from a &str and only splits at byte boundaries that preserve UTF-8 validity). Justifies uses-unsafe, unsafe-safe, unsafe-documented, and unsafe-minimal.
src/adapter/strip.rs, line 114-144
#[inline]
fn next_str<'s>(bytes: &mut &'s [u8], state: &mut State) -> Option<&'s str> {
let offset = bytes.iter().copied().position(|b| {
let (next_state, action) = state_change(*state, b);
if next_state != State::Anywhere {
*state = next_state;
}
is_printable_bytes(action, b)
});
let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
*state = State::Ground;
let offset = bytes.iter().copied().position(|b| {
let (_next_state, action) = state_change(State::Ground, b);
!(is_printable_bytes(action, b) || is_utf8_continuation(b))
});
let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
if printable.is_empty() {
None
} else {
let printable = unsafe {
from_utf8_unchecked(
printable,
"`bytes` was validated as UTF-8, the parser preserves UTF-8 continuations",
)
};
Some(printable)
}
}
The ANSI escape code parser is implemented in src/adapter/strip.rs and src/adapter/wincon.rs. It consumes byte-by-byte state from anstyle_parse::state::state_change, then classifies bytes as printable or escape-sequence bytes. The next_str and next_bytes functions iterate input slices without allocating per-byte. The parser is exercised by proptest-based property tests (strip_str_no_escapes, strip_bytes_no_escapes, strip_char_no_escapes, strip_byte_no_escapes) that generate arbitrary Unicode strings and compare against a reference full-parser implementation. These tests use proptest and are annotated #[cfg_attr(miri, ignore)], indicating the test suite has been run under Miri (where it would catch UB in the unsafe block). Justifies impl-parser, parser-impl-safe, parser-impl-tested, and unsafe-tested.