Skip to content

Commit 4ea014e

Browse files
Danilo Krummrichfbq
authored andcommitted
rust: str: test: replace alloc::format
The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Reviewed-by: Alice Ryhl <aliceryhl@google.com> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20240816001216.26575-24-dakr@kernel.org
1 parent 29c01de commit 4ea014e

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

rust/kernel/str.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,28 @@ macro_rules! c_str {
523523
#[cfg(test)]
524524
mod tests {
525525
use super::*;
526-
use alloc::format;
526+
527+
struct String(CString);
528+
529+
impl String {
530+
fn from_fmt(args: fmt::Arguments<'_>) -> Self {
531+
String(CString::try_from_fmt(args).unwrap())
532+
}
533+
}
534+
535+
impl Deref for String {
536+
type Target = str;
537+
538+
fn deref(&self) -> &str {
539+
self.0.to_str().unwrap()
540+
}
541+
}
542+
543+
macro_rules! format {
544+
($($f:tt)*) => ({
545+
&*String::from_fmt(kernel::fmt!($($f)*))
546+
})
547+
}
527548

528549
const ALL_ASCII_CHARS: &'static str =
529550
"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\

0 commit comments

Comments
 (0)