File tree Expand file tree Collapse file tree 2 files changed +44
-1
lines changed
Expand file tree Collapse file tree 2 files changed +44
-1
lines changed Original file line number Diff line number Diff line change @@ -101,7 +101,7 @@ pub use crate::utils::{
101101#[ cfg( all( feature = "ansi-parsing" , feature = "alloc" ) ) ]
102102pub 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" ) ]
107107mod common_term;
@@ -120,3 +120,5 @@ mod windows_term;
120120
121121#[ cfg( feature = "ansi-parsing" ) ]
122122mod ansi;
123+ #[ cfg( feature = "ansi-parsing" ) ]
124+ mod without_ansi;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments