Skip to content

Commit

Permalink
Avoid unnecessary copies if there is nothing to escape (#80)
Browse files Browse the repository at this point in the history
* Avoid unnecessary copies if there is nothing to escape

* Pacify clippy so CI goes green
  • Loading branch information
Byron authored Jul 14, 2020
1 parent 18b5ff8 commit 25f29cc
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,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 @@ -408,9 +409,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 @@ -421,6 +422,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 @@ -436,7 +440,7 @@ impl ColoredString {
}
}

input
input.into()
}
}

Expand Down Expand Up @@ -589,7 +593,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

0 comments on commit 25f29cc

Please sign in to comment.