|
18 | 18 | //!
|
19 | 19 | //! # fn foo() -> io::Result<()> {
|
20 | 20 | //! 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); |
22 | 22 | //! io::stdout().write_all(&plain_bytes)?;
|
23 | 23 | //! # Ok(())
|
24 | 24 | //! # }
|
@@ -59,14 +59,36 @@ where
|
59 | 59 | /// See [the module documentation][mod] for an example.
|
60 | 60 | ///
|
61 | 61 | /// [mod]: index.html
|
62 |
| -pub fn strip<T>(data: T) -> io::Result<Vec<u8>> |
| 62 | +pub fn strip<T>(data: T) -> Vec<u8> |
63 | 63 | where
|
64 | 64 | T: AsRef<[u8]>,
|
65 | 65 | {
|
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") |
70 | 92 | }
|
71 | 93 |
|
72 | 94 | struct Performer<W>
|
@@ -162,7 +184,7 @@ mod tests {
|
162 | 184 | use super::*;
|
163 | 185 |
|
164 | 186 | fn assert_parsed(input: &[u8], expected: &[u8]) {
|
165 |
| - let bytes = strip(input).expect("Failed to strip escapes"); |
| 187 | + let bytes = strip(input); |
166 | 188 | assert_eq!(bytes, expected);
|
167 | 189 | }
|
168 | 190 |
|
|
0 commit comments