Skip to content

Commit

Permalink
Merge pull request #9 from flaviojs/print-pointer-addresses
Browse files Browse the repository at this point in the history
Print pointer addresses with %p.
  • Loading branch information
tjol authored Jul 14, 2024
2 parents ede689f + 0afdeb9 commit ae82e03
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 @@ -527,3 +527,21 @@ impl Printf for CString {
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::{TryFrom, TryInto};
use std::ffi::CString;
use std::mem::size_of;
use std::os::raw::c_char;

use libc::snprintf;
Expand Down Expand Up @@ -133,3 +134,28 @@ fn test_sanity() {
assert!(bytes.len() > 1);
assert_eq!(sprintf!("%c", bytes[0]), Err(PrintfError::WrongType));
}

#[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 the same as libc 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 ae82e03

Please sign in to comment.