escape.rs 855 B

12345678910111213141516171819202122232425
  1. use ansi_term::{ANSIString, Style};
  2. pub fn escape<'a>(string: String, bits: &mut Vec<ANSIString<'a>>, good: Style, bad: Style) {
  3. if string.chars().all(|c| c >= 0x20 as char) {
  4. bits.push(good.paint(string));
  5. }
  6. else {
  7. for c in string.chars() {
  8. // The `escape_default` method on `char` is *almost* what we want here, but
  9. // it still escapes non-ASCII UTF-8 characters, which are still printable.
  10. if c >= 0x20 as char {
  11. // TODO: This allocates way too much,
  12. // hence the `all` check above.
  13. let mut s = String::new();
  14. s.push(c);
  15. bits.push(good.paint(s));
  16. } else {
  17. let s = c.escape_default().collect::<String>();
  18. bits.push(bad.paint(s));
  19. }
  20. }
  21. }
  22. }