Skip to content

Commit b055764

Browse files
Danilo Krummrichfbq
Danilo Krummrich
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 <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Reviewed-by: Gary Guo <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent 5ee077e commit b055764

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

rust/kernel/str.rs

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

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

0 commit comments

Comments
 (0)