about summary refs log tree commit diff
path: root/src/libcore/fmt
diff options
context:
space:
mode:
authorSimon Sapin <simon.sapin@exyr.org>2018-03-13 14:08:15 +0100
committerSimon Sapin <simon.sapin@exyr.org>2018-03-13 14:53:06 +0100
commit4897935e8645e5f1d9d9ef61c78a1cb019c44f89 (patch)
treed32522f913ff690cfe6893ffe68d04d0ca2c2008 /src/libcore/fmt
parent883e74645d350b6752cb94d48f46363f6f8789e9 (diff)
downloadrust-4897935e8645e5f1d9d9ef61c78a1cb019c44f89.tar.gz
rust-4897935e8645e5f1d9d9ef61c78a1cb019c44f89.zip
Add hexadecimal formatting of integers with fmt::Debug
This can be used for integers within a larger types which implements Debug
(possibly through derive) but not fmt::UpperHex or fmt::LowerHex.

```rust
assert!(format!("{:02x?}", b"Foo\0") == "[46, 6f, 6f, 00]");
assert!(format!("{:02X?}", b"Foo\0") == "[46, 6F, 6F, 00]");
```

RFC: https://github.com/rust-lang/rfcs/pull/2226
Diffstat (limited to 'src/libcore/fmt')
-rw-r--r--src/libcore/fmt/mod.rs8
-rw-r--r--src/libcore/fmt/num.rs8
2 files changed, 14 insertions, 2 deletions
diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs
index 8ad5a9861a0..a31be0e216f 100644
--- a/src/libcore/fmt/mod.rs
+++ b/src/libcore/fmt/mod.rs
@@ -333,7 +333,7 @@ impl<'a> ArgumentV1<'a> {
 
 // flags available in the v1 format of format_args
 #[derive(Copy, Clone)]
-enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
+enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
 
 impl<'a> Arguments<'a> {
     /// When using the format_args!() macro, this function is used to generate the
@@ -1401,6 +1401,12 @@ impl<'a> Formatter<'a> {
         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
     }
 
+    // FIXME: Decide what public API we want for these two flags.
+    // https://github.com/rust-lang/rust/issues/48584
+    fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
+
+    fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
+
     /// Creates a [`DebugStruct`] builder designed to assist with creation of
     /// [`fmt::Debug`] implementations for structs.
     ///
diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs
index 2992e7cf8db..86f1b5a8f28 100644
--- a/src/libcore/fmt/num.rs
+++ b/src/libcore/fmt/num.rs
@@ -159,7 +159,13 @@ macro_rules! debug {
         impl fmt::Debug for $T {
             #[inline]
             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-                fmt::Display::fmt(self, f)
+                if f.debug_lower_hex() {
+                    fmt::LowerHex::fmt(self, f)
+                } else if f.debug_upper_hex() {
+                    fmt::UpperHex::fmt(self, f)
+                } else {
+                    fmt::Display::fmt(self, f)
+                }
             }
         }
     }