Skip to content

Commit

Permalink
Print pointer addresses with %p.
Browse files Browse the repository at this point in the history
  • Loading branch information
flaviojs committed Jul 13, 2024
1 parent b89225e commit 16e8971
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,3 +475,21 @@ impl Printf for String {
None
}
}

impl<T> Printf for *const T {
fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
(*self as usize).format(spec)
}
fn as_int(&self) -> Option<i32> {
None
}
}

impl<T> Printf for *mut T {
fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
(*self as usize).format(spec)
}
fn as_int(&self) -> Option<i32> {
None
}
}
26 changes: 26 additions & 0 deletions tests/compare_to_libc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::convert::TryInto;
use std::ffi::CString;
use std::mem::size_of;
use std::os::raw::c_char;

use libc::snprintf;
Expand Down Expand Up @@ -113,3 +114,28 @@ fn test_str() {
check_fmt_s("test %% with string: %s yay\n", "FOO");
check_fmt("test char %c", '~');
}

#[test]
fn test_ptr() {
let buf: [u8; 4] = [0; 4];
let ptr_const: *const u8 = buf.as_ptr();
let ptr_mut: *mut u8 = ptr_const.cast_mut();

// pointer: expects usize and pointer to have the same size
assert_eq!(size_of::<usize>(), size_of::<*const u8>(),);
check_fmt("%p", ptr_const);
check_fmt("%p", ptr_mut);

// numeric: works if you use the correct length specifier
if size_of::<usize>() == size_of::<u64>() {
check_fmt("%llx", ptr_const);
check_fmt("%llx", ptr_mut);
check_fmt("%#llx", ptr_const);
check_fmt("%#llx", ptr_mut);
} else if size_of::<usize>() == size_of::<u32>() {
check_fmt("%x", ptr_const);
check_fmt("%x", ptr_mut);
check_fmt("%#x", ptr_const);
check_fmt("%#x", ptr_mut);
}
}

0 comments on commit 16e8971

Please sign in to comment.