Skip to content

Commit ed79884

Browse files
committed
fmt: {:p#} formats pointers padded to native width
1 parent 6436e34 commit ed79884

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

Diff for: src/libcore/fmt/mod.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -847,9 +847,33 @@ impl Display for char {
847847
#[stable(feature = "rust1", since = "1.0.0")]
848848
impl<T> Pointer for *const T {
849849
fn fmt(&self, f: &mut Formatter) -> Result {
850+
let old_width = f.width;
851+
let old_flags = f.flags;
852+
853+
// The alternate flag is already treated by LowerHex as being special-
854+
// it denotes whether to prefix with 0x. We use it to work out whether
855+
// or not to zero extend, and then unconditionally set it to get the
856+
// prefix.
857+
if f.flags & 1 << (FlagV1::Alternate as u32) > 0 {
858+
f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
859+
860+
if let None = f.width {
861+
// The formats need two extra bytes, for the 0x
862+
if cfg!(target_pointer_width = "32") {
863+
f.width = Some(10);
864+
}
865+
if cfg!(target_pointer_width = "64") {
866+
f.width = Some(18);
867+
}
868+
}
869+
}
850870
f.flags |= 1 << (FlagV1::Alternate as u32);
871+
851872
let ret = LowerHex::fmt(&(*self as usize), f);
852-
f.flags &= !(1 << (FlagV1::Alternate as u32));
873+
874+
f.width = old_width;
875+
f.flags = old_flags;
876+
853877
ret
854878
}
855879
}

Diff for: src/test/run-pass/fmt-pointer-trait.rs

+8
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ fn main() {
2323
let _ = format!("{:p}{:p}{:p}",
2424
rc, arc, b);
2525

26+
if cfg!(target_pointer_width = "32") {
27+
assert_eq!(format!("{:#p}", p),
28+
"0x00000000");
29+
}
30+
if cfg!(target_pointer_width = "64") {
31+
assert_eq!(format!("{:#p}", p),
32+
"0x0000000000000000");
33+
}
2634
assert_eq!(format!("{:p}", p),
2735
"0x0");
2836
}

Diff for: src/test/run-pass/ifmt.rs

+6
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ impl fmt::Display for C {
4242
macro_rules! t {
4343
($a:expr, $b:expr) => { assert_eq!($a, $b) }
4444
}
45+
#[cfg(target_pointer_width = "32")]
46+
const PTR: &'static str = "0x00001234";
47+
#[cfg(target_pointer_width = "64")]
48+
const PTR: &'static str = "0x0000000000001234";
4549

4650
pub fn main() {
4751
// Various edge cases without formats
@@ -72,6 +76,8 @@ pub fn main() {
7276
t!(format!("{:X}", 10_usize), "A");
7377
t!(format!("{}", "foo"), "foo");
7478
t!(format!("{}", "foo".to_string()), "foo");
79+
t!(format!("{:#p}", 0x1234 as *const isize), PTR);
80+
t!(format!("{:#p}", 0x1234 as *mut isize), PTR);
7581
t!(format!("{:p}", 0x1234 as *const isize), "0x1234");
7682
t!(format!("{:p}", 0x1234 as *mut isize), "0x1234");
7783
t!(format!("{:x}", A), "aloha");

0 commit comments

Comments
 (0)