From 16e89715edf157477f2ae68728e93a2761b56794 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fl=C3=A1vio=20J=2E=20Saraiva?= Date: Sat, 13 Jul 2024 21:47:30 +0100 Subject: [PATCH] Print pointer addresses with %p. --- src/format.rs | 18 ++++++++++++++++++ tests/compare_to_libc.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/format.rs b/src/format.rs index ee4489c..152ca8f 100644 --- a/src/format.rs +++ b/src/format.rs @@ -475,3 +475,21 @@ impl Printf for String { None } } + +impl Printf for *const T { + fn format(&self, spec: &ConversionSpecifier) -> Result { + (*self as usize).format(spec) + } + fn as_int(&self) -> Option { + None + } +} + +impl Printf for *mut T { + fn format(&self, spec: &ConversionSpecifier) -> Result { + (*self as usize).format(spec) + } + fn as_int(&self) -> Option { + None + } +} diff --git a/tests/compare_to_libc.rs b/tests/compare_to_libc.rs index da1b0e4..a0db0a0 100644 --- a/tests/compare_to_libc.rs +++ b/tests/compare_to_libc.rs @@ -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; @@ -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::(), 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::() == size_of::() { + check_fmt("%llx", ptr_const); + check_fmt("%llx", ptr_mut); + check_fmt("%#llx", ptr_const); + check_fmt("%#llx", ptr_mut); + } else if size_of::() == size_of::() { + check_fmt("%x", ptr_const); + check_fmt("%x", ptr_mut); + check_fmt("%#x", ptr_const); + check_fmt("%#x", ptr_mut); + } +}