Skip to content

Commit 672ce55

Browse files
authored
Merge pull request #11 from sunshowers/more-strip
Improvements to strip
2 parents f42c49e + 6c55071 commit 672ce55

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::io::{self, Write};
1616

1717
fn work() -> io::Result<()> {
1818
let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
19-
let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors)?;
19+
let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors);
2020
io::stdout().write_all(&plain_bytes)?;
2121
Ok(())
2222
}

src/lib.rs

+29-7
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
//!
1919
//! # fn foo() -> io::Result<()> {
2020
//! let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
21-
//! let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors)?;
21+
//! let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors);
2222
//! io::stdout().write_all(&plain_bytes)?;
2323
//! # Ok(())
2424
//! # }
@@ -59,14 +59,36 @@ where
5959
/// See [the module documentation][mod] for an example.
6060
///
6161
/// [mod]: index.html
62-
pub fn strip<T>(data: T) -> io::Result<Vec<u8>>
62+
pub fn strip<T>(data: T) -> Vec<u8>
6363
where
6464
T: AsRef<[u8]>,
6565
{
66-
let c = Cursor::new(Vec::new());
67-
let mut writer = Writer::new(c);
68-
writer.write_all(data.as_ref())?;
69-
Ok(writer.into_inner()?.into_inner())
66+
fn strip_impl(data: &[u8]) -> io::Result<Vec<u8>> {
67+
let c = Cursor::new(Vec::new());
68+
let mut writer = Writer::new(c);
69+
writer.write_all(data.as_ref())?;
70+
Ok(writer.into_inner()?.into_inner())
71+
}
72+
73+
strip_impl(data.as_ref()).expect("writing to a Cursor<Vec<u8>> cannot fail")
74+
}
75+
76+
/// Strip ANSI escapes from `data` and return the remaining contents as a `String`.
77+
///
78+
/// # Example
79+
///
80+
/// ```
81+
/// let str_with_colors = "\x1b[32mfoo\x1b[m bar";
82+
/// let string_without_colors = strip_ansi_escapes::strip_str(string_with_colors);
83+
/// assert_eq!(string_without_colors, "foo bar");
84+
/// ```
85+
pub fn strip_str<T>(data: T) -> String
86+
where
87+
T: AsRef<str>,
88+
{
89+
let bytes = strip(data.as_ref());
90+
String::from_utf8(bytes)
91+
.expect("stripping ANSI escapes from a UTF-8 string always results in UTF-8")
7092
}
7193

7294
struct Performer<W>
@@ -162,7 +184,7 @@ mod tests {
162184
use super::*;
163185

164186
fn assert_parsed(input: &[u8], expected: &[u8]) {
165-
let bytes = strip(input).expect("Failed to strip escapes");
187+
let bytes = strip(input);
166188
assert_eq!(bytes, expected);
167189
}
168190

0 commit comments

Comments
 (0)