Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements to strip #11

Merged
merged 2 commits into from
Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::io::{self, Write};

fn work() -> io::Result<()> {
let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors)?;
let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors);
io::stdout().write_all(&plain_bytes)?;
Ok(())
}
Expand Down
36 changes: 29 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
//!
//! # fn foo() -> io::Result<()> {
//! let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
//! let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors)?;
//! let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors);
//! io::stdout().write_all(&plain_bytes)?;
//! # Ok(())
//! # }
Expand Down Expand Up @@ -59,14 +59,36 @@ where
/// See [the module documentation][mod] for an example.
///
/// [mod]: index.html
pub fn strip<T>(data: T) -> io::Result<Vec<u8>>
pub fn strip<T>(data: T) -> Vec<u8>
where
T: AsRef<[u8]>,
{
let c = Cursor::new(Vec::new());
let mut writer = Writer::new(c);
writer.write_all(data.as_ref())?;
Ok(writer.into_inner()?.into_inner())
fn strip_impl(data: &[u8]) -> io::Result<Vec<u8>> {
let c = Cursor::new(Vec::new());
let mut writer = Writer::new(c);
writer.write_all(data.as_ref())?;
Ok(writer.into_inner()?.into_inner())
}

strip_impl(data.as_ref()).expect("writing to a Cursor<Vec<u8>> cannot fail")
}

/// Strip ANSI escapes from `data` and return the remaining contents as a `String`.
///
/// # Example
///
/// ```
/// let str_with_colors = "\x1b[32mfoo\x1b[m bar";
/// let string_without_colors = strip_ansi_escapes::strip_str(string_with_colors);
/// assert_eq!(string_without_colors, "foo bar");
/// ```
pub fn strip_str<T>(data: T) -> String
where
T: AsRef<str>,
{
let bytes = strip(data.as_ref());
String::from_utf8(bytes)
.expect("stripping ANSI escapes from a UTF-8 string always results in UTF-8")
}

struct Performer<W>
Expand Down Expand Up @@ -162,7 +184,7 @@ mod tests {
use super::*;

fn assert_parsed(input: &[u8], expected: &[u8]) {
let bytes = strip(input).expect("Failed to strip escapes");
let bytes = strip(input);
assert_eq!(bytes, expected);
}

Expand Down