|
1 | 1 | use core::convert::TryFrom;
|
2 |
| -use core::{char, fmt, mem}; |
| 2 | +use core::{char, fmt, iter, mem}; |
3 | 3 |
|
4 | 4 | #[allow(unused_macros)]
|
5 | 5 | macro_rules! write {
|
@@ -604,6 +604,35 @@ impl<'a, 'b, 's> Printer<'a, 'b, 's> {
|
604 | 604 | Ok(())
|
605 | 605 | }
|
606 | 606 |
|
| 607 | + /// Output the given `char`s (escaped using `char::escape_debug`), with the |
| 608 | + /// whole sequence wrapped in quotes, for either a `char` or `&str` literal, |
| 609 | + /// if printing isn't being skipped. |
| 610 | + fn print_quoted_escaped_chars( |
| 611 | + &mut self, |
| 612 | + quote: char, |
| 613 | + chars: impl Iterator<Item = char>, |
| 614 | + ) -> fmt::Result { |
| 615 | + if let Some(out) = &mut self.out { |
| 616 | + use core::fmt::Write; |
| 617 | + |
| 618 | + out.write_char(quote)?; |
| 619 | + for c in chars { |
| 620 | + // Special-case not escaping a single/double quote, when |
| 621 | + // inside the opposite kind of quote. |
| 622 | + if matches!((quote, c), ('\'', '"') | ('"', '\'')) { |
| 623 | + out.write_char(c)?; |
| 624 | + continue; |
| 625 | + } |
| 626 | + |
| 627 | + for escaped in c.escape_debug() { |
| 628 | + out.write_char(escaped)?; |
| 629 | + } |
| 630 | + } |
| 631 | + out.write_char(quote)?; |
| 632 | + } |
| 633 | + Ok(()) |
| 634 | + } |
| 635 | + |
607 | 636 | /// Print the lifetime according to the previously decoded index.
|
608 | 637 | /// An index of `0` always refers to `'_`, but starting with `1`,
|
609 | 638 | /// indices refer to late-bound lifetimes introduced by a binder.
|
@@ -1000,11 +1029,7 @@ impl<'a, 'b, 's> Printer<'a, 'b, 's> {
|
1000 | 1029 | .and_then(|v| u32::try_from(v).ok())
|
1001 | 1030 | .and_then(char::from_u32);
|
1002 | 1031 | match valid_char {
|
1003 |
| - Some(c) => { |
1004 |
| - if let Some(out) = &mut self.out { |
1005 |
| - fmt::Debug::fmt(&c, out)?; |
1006 |
| - } |
1007 |
| - } |
| 1032 | + Some(c) => self.print_quoted_escaped_chars('\'', iter::once(c))?, |
1008 | 1033 | None => invalid!(self),
|
1009 | 1034 | }
|
1010 | 1035 | }
|
|
0 commit comments