Skip to content

Commit 9c0e5eb

Browse files
committed
fix Debug impl for AsciiChar
1 parent dc348db commit 9c0e5eb

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

library/core/src/ascii/ascii_char.rs

+39-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! suggestions from rustc if you get anything slightly wrong in here, and overall
44
//! helps with clarity as we're also referring to `char` intentionally in here.
55
6-
use crate::fmt;
6+
use crate::fmt::{self, Write};
77
use crate::mem::transmute;
88

99
/// One of the 128 Unicode characters from U+0000 through U+007F,
@@ -54,7 +54,7 @@ use crate::mem::transmute;
5454
/// [chart]: https://www.unicode.org/charts/PDF/U0000.pdf
5555
/// [NIST FIPS 1-2]: https://nvlpubs.nist.gov/nistpubs/Legacy/FIPS/fipspub1-2-1977.pdf
5656
/// [NamesList]: https://www.unicode.org/Public/15.0.0/ucd/NamesList.txt
57-
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
57+
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
5858
#[unstable(feature = "ascii_char", issue = "110998")]
5959
#[repr(u8)]
6060
pub enum AsciiChar {
@@ -563,3 +563,40 @@ impl fmt::Display for AsciiChar {
563563
<str as fmt::Display>::fmt(self.as_str(), f)
564564
}
565565
}
566+
567+
#[unstable(feature = "ascii_char", issue = "110998")]
568+
impl fmt::Debug for AsciiChar {
569+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570+
#[inline]
571+
fn backslash(a: AsciiChar) -> ([AsciiChar; 4], u8) {
572+
([AsciiChar::ReverseSolidus, a, AsciiChar::Null, AsciiChar::Null], 2)
573+
}
574+
575+
let (buf, len) = match self {
576+
AsciiChar::Null => backslash(AsciiChar::Digit0),
577+
AsciiChar::CharacterTabulation => backslash(AsciiChar::SmallT),
578+
AsciiChar::CarriageReturn => backslash(AsciiChar::SmallR),
579+
AsciiChar::LineFeed => backslash(AsciiChar::SmallN),
580+
AsciiChar::ReverseSolidus => backslash(AsciiChar::ReverseSolidus),
581+
AsciiChar::Apostrophe => backslash(AsciiChar::Apostrophe),
582+
_ => {
583+
let byte = self.to_u8();
584+
if !byte.is_ascii_control() {
585+
([*self, AsciiChar::Null, AsciiChar::Null, AsciiChar::Null], 1)
586+
} else {
587+
const HEX_DIGITS: [AsciiChar; 16] = *b"0123456789abcdef".as_ascii().unwrap();
588+
589+
let hi = HEX_DIGITS[usize::from(byte >> 4)];
590+
let lo = HEX_DIGITS[usize::from(byte & 0xf)];
591+
([AsciiChar::ReverseSolidus, AsciiChar::SmallX, hi, lo], 4)
592+
}
593+
}
594+
};
595+
596+
f.write_char('\'')?;
597+
for byte in &buf[..len as usize] {
598+
f.write_str(byte.as_str())?;
599+
}
600+
f.write_char('\'')
601+
}
602+
}

0 commit comments

Comments
 (0)