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

Avoid unnecessary copies if there is nothing to escape #80

Merged
merged 2 commits into from
Jul 14, 2020
Merged
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
12 changes: 8 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use std::convert::From;
use std::fmt;
use std::ops::Deref;
use std::string::String;
use std::borrow::Cow;

pub use style::{Style, Styles};

Expand Down Expand Up @@ -394,9 +395,9 @@ impl ColoredString {
res
}

fn escape_inner_reset_sequences(&self) -> String {
fn escape_inner_reset_sequences(&self) -> Cow<str> {
if !self.has_colors() || self.is_plain() {
return self.input.clone();
return self.input.as_str().into();
}

// TODO: BoyScoutRule
Expand All @@ -407,6 +408,9 @@ impl ColoredString {
.match_indices(reset)
.map(|(idx, _)| idx)
.collect();
if matches.is_empty() {
return self.input.as_str().into()
}

let mut input = self.input.clone();
input.reserve(matches.len() * style.len());
Expand All @@ -422,7 +426,7 @@ impl ColoredString {
}
}

input
input.into()
}
}

Expand Down Expand Up @@ -575,7 +579,7 @@ impl fmt::Display for ColoredString {
let escaped_input = self.escape_inner_reset_sequences();

f.write_str(&self.compute_style())?;
<String as fmt::Display>::fmt(&escaped_input, f)?;
escaped_input.fmt(f)?;
f.write_str("\x1B[0m")?;
Ok(())
}
Expand Down