Skip to content

Commit 0dc5643

Browse files
committed
fmt: Pad pointers to native pointer width
1 parent a329a61 commit 0dc5643

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

src/libcore/fmt/mod.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,12 +844,29 @@ 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 {
850856
f.flags |= 1 << (FlagV1::Alternate as u32);
857+
f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
858+
859+
let old_width = f.width;
860+
if let None = f.width {
861+
f.width = POINTER_PADDING;
862+
}
863+
851864
let ret = LowerHex::fmt(&(*self as usize), f);
865+
866+
f.width = old_width;
852867
f.flags &= !(1 << (FlagV1::Alternate as u32));
868+
f.flags &= !(1 << (FlagV1::SignAwareZeroPad as u32));
869+
853870
ret
854871
}
855872
}

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

Lines changed: 6 additions & 1 deletion
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);
@@ -24,5 +29,5 @@ fn main() {
2429
rc, arc, b);
2530

2631
assert_eq!(format!("{:p}", p),
27-
"0x0");
32+
PTR.to_string());
2833
}

src/test/run-pass/ifmt.rs

Lines changed: 6 additions & 2 deletions
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,8 +76,8 @@ pub fn main() {
7276
t!(format!("{:X}", 10_usize), "A");
7377
t!(format!("{}", "foo"), "foo");
7478
t!(format!("{}", "foo".to_string()), "foo");
75-
t!(format!("{:p}", 0x1234 as *const isize), "0x1234");
76-
t!(format!("{:p}", 0x1234 as *mut isize), "0x1234");
79+
t!(format!("{:p}", 0x1234 as *const isize), PTR);
80+
t!(format!("{:p}", 0x1234 as *mut isize), PTR);
7781
t!(format!("{:x}", A), "aloha");
7882
t!(format!("{:X}", B), "adios");
7983
t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃");

0 commit comments

Comments
 (0)