Skip to content

Commit 178c47e

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

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

src/libcore/fmt/mod.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -844,12 +844,32 @@ impl Display for char {
844844
}
845845
}
846846

847+
// Two extra bytes for 0x
848+
#[cfg(target_pointer_width = "32")]
849+
const POINTER_PADDING: Option<usize> = Some(10);
850+
#[cfg(target_pointer_width = "64")]
851+
const POINTER_PADDING: Option<usize> = Some(18);
852+
847853
#[stable(feature = "rust1", since = "1.0.0")]
848854
impl<T> Pointer for *const T {
849855
fn fmt(&self, f: &mut Formatter) -> Result {
856+
let old_width = f.width;
857+
let old_flags = f.flags;
858+
859+
if f.flags & 1 << (FlagV1::Alternate as u32) > 0 {
860+
f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
861+
862+
if let None = f.width {
863+
f.width = POINTER_PADDING;
864+
}
865+
}
850866
f.flags |= 1 << (FlagV1::Alternate as u32);
867+
851868
let ret = LowerHex::fmt(&(*self as usize), f);
852-
f.flags &= !(1 << (FlagV1::Alternate as u32));
869+
870+
f.width = old_width;
871+
f.flags = old_flags;
872+
853873
ret
854874
}
855875
}

src/test/run-pass/fmt-pointer-trait.rs

+7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ use std::ptr;
1414
use std::rc::Rc;
1515
use std::sync::Arc;
1616

17+
#[cfg(target_pointer_width = "32")]
18+
const PTR: &'static str = "0x00000000";
19+
#[cfg(target_pointer_width = "64")]
20+
const PTR: &'static str = "0x0000000000000000";
21+
1722
fn main() {
1823
let p: *const libc::c_void = ptr::null();
1924
let rc = Rc::new(1usize);
@@ -23,6 +28,8 @@ fn main() {
2328
let _ = format!("{:p}{:p}{:p}",
2429
rc, arc, b);
2530

31+
assert_eq!(format!("{:#p}", p),
32+
PTR.to_string());
2633
assert_eq!(format!("{:p}", p),
2734
"0x0");
2835
}

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)