Skip to content

Commit 5613ddf

Browse files
Add WithoutAnsi struct that implements Display
1 parent a9492df commit 5613ddf

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/lib.rs

Lines changed: 3 additions & 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, without_ansi::WithoutAnsi};
105105

106106
#[cfg(feature = "std")]
107107
mod common_term;
@@ -120,3 +120,5 @@ mod windows_term;
120120

121121
#[cfg(feature = "ansi-parsing")]
122122
mod ansi;
123+
#[cfg(feature = "ansi-parsing")]
124+
mod without_ansi;

src/without_ansi.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
use core::fmt::Display;
2+
3+
use crate::AnsiCodeIterator;
4+
5+
/// A wrapper struct that implements [`core::fmt::Display`], only displaying non-ansi parts.
6+
pub struct WithoutAnsi<'a> {
7+
str: &'a str,
8+
}
9+
impl<'a> WithoutAnsi<'a> {
10+
pub fn new(str: &'a str) -> Self {
11+
Self { str }
12+
}
13+
}
14+
impl Display for WithoutAnsi<'_> {
15+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
16+
for str in
17+
AnsiCodeIterator::new(self.str)
18+
.filter_map(|(str, is_ansi)| if is_ansi { None } else { Some(str) })
19+
{
20+
f.write_str(str)?;
21+
}
22+
Ok(())
23+
}
24+
}
25+
26+
#[cfg(test)]
27+
mod tests {
28+
use super::*;
29+
use core::fmt::Write;
30+
31+
#[test]
32+
fn display_multiple_times() {
33+
let str_with_ansi = "\x1b[1;97;41mError\x1b[0m";
34+
let without_ansi = WithoutAnsi::new(str_with_ansi);
35+
for _ in 0..2 {
36+
let mut output = String::default();
37+
write!(output, "{without_ansi}").unwrap();
38+
assert_eq!(output, "Error");
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)