Skip to content

Commit

Permalink
fmt: {:p#} formats pointers padded to native width
Browse files Browse the repository at this point in the history
  • Loading branch information
richo committed Apr 10, 2015
1 parent 6436e34 commit 333eb85
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/libcore/fmt/mod.rs
Expand Up @@ -847,9 +847,33 @@ impl Display for char {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
let old_width = f.width;
let old_flags = f.flags;

// The alternate flag is already treated by LowerHex as being special-
// it denotes whether to prefix with 0x. We use it to work out whether
// or not to zero extend, and then unconditionally set it to get the
// prefix.
if f.flags & 1 << (FlagV1::Alternate as u32) > 0 {
f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);

if let None = f.width {
// The formats need two extra bytes, for the 0x
if cfg!(target_pointer_width = "32") {
f.width = Some(10);
}
if cfg!(target_pointer_width = "64") {
f.width = Some(18);
}
}
}
f.flags |= 1 << (FlagV1::Alternate as u32);

let ret = LowerHex::fmt(&(*self as usize), f);
f.flags &= !(1 << (FlagV1::Alternate as u32));

f.width = old_width;
f.flags = old_flags;

ret
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/test/run-pass/fmt-pointer-trait.rs
Expand Up @@ -23,6 +23,14 @@ fn main() {
let _ = format!("{:p}{:p}{:p}",
rc, arc, b);

if cfg!(target_pointer_width = "32") {
assert_eq!(format!("{:#p}", p),
"0x00000000");
}
if cfg!(target_pointer_width = "64") {
assert_eq!(format!("{:#p}", p),
"0x0000000000000000");
}
assert_eq!(format!("{:p}", p),
"0x0");
}
8 changes: 8 additions & 0 deletions src/test/run-pass/ifmt.rs
Expand Up @@ -72,6 +72,14 @@ pub fn main() {
t!(format!("{:X}", 10_usize), "A");
t!(format!("{}", "foo"), "foo");
t!(format!("{}", "foo".to_string()), "foo");
if cfg!(target_pointer_width = "32") {
t!(format!("{:#p}", 0x1234 as *const isize), "0x00001234");
t!(format!("{:#p}", 0x1234 as *mut isize), "0x00001234");
}
if cfg!(target_pointer_width = "64") {
t!(format!("{:#p}", 0x1234 as *const isize), "0x0000000000001234");
t!(format!("{:#p}", 0x1234 as *mut isize), "0x0000000000001234");
}
t!(format!("{:p}", 0x1234 as *const isize), "0x1234");
t!(format!("{:p}", 0x1234 as *mut isize), "0x1234");
t!(format!("{:x}", A), "aloha");
Expand Down

0 comments on commit 333eb85

Please sign in to comment.