Skip to content

Commit 903df6d

Browse files
ChocolateLoverRajdjc
authored andcommitted
Add WithoutAnsi struct that implements Display
1 parent bda6a6e commit 903df6d

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/ansi.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#[cfg(feature = "alloc")]
22
use alloc::{borrow::Cow, string::String};
33
use core::{
4+
fmt::Display,
45
iter::{FusedIterator, Peekable},
56
str::CharIndices,
67
};
@@ -201,6 +202,27 @@ pub fn strip_ansi_codes(s: &str) -> Cow<str> {
201202
}
202203
}
203204

205+
/// A wrapper struct that implements [`core::fmt::Display`], only displaying non-ansi parts.
206+
pub struct WithoutAnsi<'a> {
207+
str: &'a str,
208+
}
209+
impl<'a> WithoutAnsi<'a> {
210+
pub fn new(str: &'a str) -> Self {
211+
Self { str }
212+
}
213+
}
214+
impl Display for WithoutAnsi<'_> {
215+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216+
for str in
217+
AnsiCodeIterator::new(self.str)
218+
.filter_map(|(str, is_ansi)| if is_ansi { None } else { Some(str) })
219+
{
220+
f.write_str(str)?;
221+
}
222+
Ok(())
223+
}
224+
}
225+
204226
/// An iterator over ansi codes in a string.
205227
///
206228
/// This type can be used to scan over ansi codes in a string.
@@ -273,6 +295,7 @@ impl FusedIterator for AnsiCodeIterator<'_> {}
273295
mod tests {
274296
use super::*;
275297

298+
use core::fmt::Write;
276299
use once_cell::sync::Lazy;
277300
use proptest::prelude::*;
278301
use regex::Regex;
@@ -385,6 +408,17 @@ mod tests {
385408
assert_eq!(&[s], matches.as_slice());
386409
}
387410

411+
#[test]
412+
fn test_without_ansi() {
413+
let str_with_ansi = "\x1b[1;97;41mError\x1b[0m";
414+
let without_ansi = WithoutAnsi::new(str_with_ansi);
415+
for _ in 0..2 {
416+
let mut output = String::default();
417+
write!(output, "{without_ansi}").unwrap();
418+
assert_eq!(output, "Error");
419+
}
420+
}
421+
388422
#[test]
389423
fn test_ansi_iter_re_vt100() {
390424
let s = "\x1b(0lpq\x1b)Benglish";

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ pub use crate::utils::{
101101
#[cfg(all(feature = "ansi-parsing", feature = "alloc"))]
102102
pub use crate::ansi::strip_ansi_codes;
103103
#[cfg(feature = "ansi-parsing")]
104-
pub use crate::ansi::AnsiCodeIterator;
104+
pub use crate::ansi::{AnsiCodeIterator, WithoutAnsi};
105105

106106
#[cfg(feature = "std")]
107107
mod common_term;

0 commit comments

Comments
 (0)