#[cfg(feature = "alloc")]
use alloc::{borrow::Cow, string::String};
const ESC: u8 = 0x1B;
const BEL: u8 = 0x07;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Piece<'a> {
Text(&'a str),
Escape(&'a str),
}
impl<'a> Piece<'a> {
pub fn as_str(&self) -> &'a str {
match *self {
Piece::Text(s) | Piece::Escape(s) => s,
}
}
pub fn is_escape(&self) -> bool {
matches!(self, Piece::Escape(_))
}
}
#[derive(Clone)]
pub struct Pieces<'a> {
s: &'a str,
pos: usize,
}
impl<'a> Pieces<'a> {
pub(crate) fn new(s: &'a str) -> Self {
Pieces { s, pos: 0 }
}
}
impl<'a> Iterator for Pieces<'a> {
type Item = Piece<'a>;
fn next(&mut self) -> Option<Piece<'a>> {
let bytes = self.s.as_bytes();
if self.pos >= bytes.len() {
return None;
}
let start = self.pos;
if let Some(len) = escape_len(bytes, start) {
self.pos = start + len;
return Some(Piece::Escape(&self.s[start..self.pos]));
}
let mut i = start;
loop {
while i < bytes.len() && bytes[i] != ESC && bytes[i] != 0xC2 {
i += 1;
}
if i >= bytes.len() || escape_len(bytes, i).is_some() {
break;
}
i += 1; }
self.pos = i;
Some(Piece::Text(&self.s[start..i]))
}
}
impl core::iter::FusedIterator for Pieces<'_> {}
pub(crate) fn escape_len(b: &[u8], i: usize) -> Option<usize> {
match *b.get(i)? {
ESC => match b.get(i + 1) {
Some(b'[') => Some(csi_len(b, i, i + 2)),
Some(b']' | b'P' | b'X' | b'^' | b'_') => Some(string_len(b, i, i + 2)),
Some(&c) if (0x20..=0x2F).contains(&c) => {
let mut j = i + 1;
while matches!(b.get(j), Some(&c) if (0x20..=0x2F).contains(&c)) {
j += 1;
}
if matches!(b.get(j), Some(&c) if (0x30..=0x7E).contains(&c)) {
j += 1;
}
Some(j - i)
}
Some(&c) if (0x30..=0x7E).contains(&c) => Some(2),
_ => Some(1),
},
0xC2 => match b.get(i + 1) {
Some(0x9B) => Some(csi_len(b, i, i + 2)),
Some(0x9D | 0x90 | 0x98 | 0x9E | 0x9F) => Some(string_len(b, i, i + 2)),
_ => None,
},
_ => None,
}
}
fn csi_len(b: &[u8], start: usize, mut j: usize) -> usize {
while matches!(b.get(j), Some(&c) if (0x30..=0x3F).contains(&c)) {
j += 1;
}
while matches!(b.get(j), Some(&c) if (0x20..=0x2F).contains(&c)) {
j += 1;
}
if matches!(b.get(j), Some(&c) if (0x40..=0x7E).contains(&c)) {
j += 1;
}
j - start
}
fn string_len(b: &[u8], start: usize, mut j: usize) -> usize {
while j < b.len() {
match b[j] {
BEL => return j + 1 - start,
ESC if b.get(j + 1) == Some(&b'\\') => return j + 2 - start,
0xC2 if b.get(j + 1) == Some(&0x9C) => return j + 2 - start,
_ => j += 1,
}
}
j - start
}
#[cfg(feature = "alloc")]
fn sgr_params(e: &str) -> Option<&str> {
let b = e.as_bytes();
if b.last() != Some(&b'm') {
return None;
}
let head = match (b.first(), b.get(1)) {
(Some(&ESC), Some(b'[')) => 2,
(Some(&0xC2), Some(&0x9B)) => 2,
_ => return None,
};
Some(&e[head..e.len() - 1])
}
#[cfg(feature = "alloc")]
pub(crate) fn leaves_style_open(s: &str) -> bool {
let mut open = false;
for piece in Pieces::new(s) {
if let Piece::Escape(e) = piece {
if let Some(params) = sgr_params(e) {
let is_reset = params.is_empty()
|| params
.split(';')
.all(|p| p.is_empty() || p.bytes().all(|c| c == b'0'));
open = !is_reset;
}
}
}
open
}
#[cfg(feature = "alloc")]
pub(crate) const RESET: &str = "\x1b[0m";
#[cfg(feature = "alloc")]
pub fn strip_ansi(s: &str) -> Cow<'_, str> {
if !has_escape(s) {
return Cow::Borrowed(s);
}
let mut buf = String::with_capacity(s.len());
for piece in Pieces::new(s) {
if let Piece::Text(t) = piece {
buf.push_str(t);
}
}
Cow::Owned(buf)
}
#[cfg(feature = "alloc")]
pub(crate) fn has_escape(s: &str) -> bool {
s.as_bytes()
.iter()
.enumerate()
.any(|(i, &c)| (c == ESC || c == 0xC2) && escape_len(s.as_bytes(), i).is_some())
}
#[cfg(feature = "alloc")]
pub(crate) fn is_terminated(e: &str) -> bool {
let b = e.as_bytes();
let n = b.len();
match (b.first(), b.get(1)) {
(Some(&ESC), Some(b'[')) | (Some(&0xC2), Some(&0x9B)) => {
n > 2 && matches!(b.last(), Some(&c) if (0x40..=0x7E).contains(&c))
}
(Some(&ESC), Some(b']' | b'P' | b'X' | b'^' | b'_'))
| (Some(&0xC2), Some(&(0x9D | 0x90 | 0x98 | 0x9E | 0x9F))) => {
n > 2
&& (b[n - 1] == BEL
|| (b[n - 2] == ESC && b[n - 1] == b'\\')
|| (b[n - 2] == 0xC2 && b[n - 1] == 0x9C))
}
(Some(&ESC), Some(&c)) if (0x20..=0x2F).contains(&c) => {
matches!(b.last(), Some(&c) if (0x30..=0x7E).contains(&c))
}
(Some(&ESC), Some(_)) => true, (Some(&ESC), None) => false, _ => true,
}
}
#[cfg(feature = "alloc")]
pub(crate) fn trim_dangling(s: &str) -> &str {
if !has_escape(s) {
return s;
}
let mut last = None;
let mut pos = 0;
for p in Pieces::new(s) {
last = match p {
Piece::Escape(e) => Some((pos, e)),
Piece::Text(_) => None,
};
pos += p.as_str().len();
}
match last {
Some((at, e)) if !is_terminated(e) => trim_dangling(&s[..at]),
_ => s,
}
}
#[cfg(all(test, feature = "alloc"))]
mod tests {
use super::*;
#[test]
fn escape_len_at_the_boundary() {
assert_eq!(escape_len(b"", 0), None);
assert_eq!(escape_len(b"ab", 2), None);
assert_eq!(escape_len(b"a", 0), None);
assert_eq!(escape_len(b"\x1b[0m", 0), Some(4));
}
#[test]
fn termination_of_every_escape_form() {
for complete in [
"\x1b[0m",
"\x1b[1;31m",
"\u{9b}0m", "\x1b]0;t\x07",
"\x1b]0;t\x1b\\", "\x1b]0;t\u{9c}",
"\x1bPq\x1b\\", "\x1b(B",
"\x1b$)C", "\x1b7",
"\x1bM", "not an escape",
"", ] {
assert!(is_terminated(complete), "{complete:?} should be complete");
}
for dangling in [
"\x1b",
"\x1b[",
"\x1b[31",
"\x1b[1;", "\x1b]",
"\x1b]8;;http://x",
"\x1bP", "\x1b$",
"\x1b ", ] {
assert!(!is_terminated(dangling), "{dangling:?} should be dangling");
}
}
}