@@ -56,6 +56,7 @@ macro_rules! kunit_assert {
break 'out;
}
+ static NAME: &'static $crate::str::CStr = $crate::c_str!($name);
static FILE: &'static $crate::str::CStr = $crate::c_str!($file);
static LINE: i32 = core::line!() as i32 - $diff;
static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
@@ -71,11 +72,13 @@ macro_rules! kunit_assert {
//
// This mimics KUnit's failed assertion format.
$crate::kunit::err(format_args!(
- " # {}: ASSERTION FAILED at {FILE}:{LINE}\n",
- $name
+ " # {NAME}: ASSERTION FAILED at {FILE}:{LINE}\n",
+ NAME = NAME.display(),
+ FILE = FILE.display(),
));
$crate::kunit::err(format_args!(
- " Expected {CONDITION} to be true, but is false\n"
+ " Expected {CONDITION} to be true, but is false\n",
+ CONDITION = CONDITION.display(),
));
$crate::kunit::err(format_args!(
" Failure not reported to KUnit since this is a non-KUnit task\n"
@@ -31,29 +31,77 @@ pub const fn from_bytes(bytes: &[u8]) -> &Self {
// SAFETY: `BStr` is transparent to `[u8]`.
unsafe { &*(bytes as *const [u8] as *const BStr) }
}
-}
-impl fmt::Display for BStr {
- /// Formats printable ASCII characters, escaping the rest.
+ /// Returns an object that implements [`Display`] for safely printing a [`BStr`] that may
+ /// contain non-Unicode data. If you would like an implementation which escapes the [`BStr`]
+ /// please use [`Debug`] instead.
+ ///
+ /// [`Display`]: fmt::Display
+ /// [`Debug`]: fmt::Debug
+ ///
+ /// # Examples
///
/// ```
- /// # use kernel::{fmt, b_str, str::{BStr, CString}};
+ /// # use kernel::{fmt, b_str, str::CString};
/// let ascii = b_str!("Hello, BStr!");
- /// let s = CString::try_from_fmt(fmt!("{}", ascii))?;
+ /// let s = CString::try_from_fmt(fmt!("{}", ascii.display()))?;
/// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes());
///
/// let non_ascii = b_str!("
There are two reasons for doing this: - Moving the Display impl behind a display method matches the style used in the standard library for printing non-Unicode data. - The standard library's core::ffi::CStr doesn't implement Display; moving Display to a helper struct is a necessary step toward using it. Signed-off-by: Tamir Duberstein <tamird@gmail.com> --- rust/kernel/kunit.rs | 9 ++-- rust/kernel/str.rs | 121 +++++++++++++++++++++++++++++++++++---------------- 2 files changed, 90 insertions(+), 40 deletions(-)