[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <20250915065401.20141-1-work@onurozkan.dev>
Date: Mon, 15 Sep 2025 09:54:01 +0300
From: Onur Özkan <work@...rozkan.dev>
To: rust-for-linux@...r.kernel.org
Cc: ojeda@...nel.org,
alex.gaynor@...il.com,
boqun.feng@...il.com,
gary@...yguo.net,
bjorn3_gh@...tonmail.com,
lossin@...nel.org,
a.hindborg@...nel.org,
aliceryhl@...gle.com,
tmgross@...ch.edu,
dakr@...nel.org,
tamird@...il.com,
daniel@...lak.dev,
linux-kernel@...r.kernel.org,
Onur Özkan <work@...rozkan.dev>
Subject: [PATCH] rust: less allocation in CString::try_from
Allocates buffer with the correct capacity upfront by
using the length of the `CStr` to avoid extra and unnecessary
re-allocation when converting from `CStr` to `CString`.
Signed-off-by: Onur Özkan <work@...rozkan.dev>
---
rust/kernel/str.rs | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 6c892550c0ba..98d41d995e45 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -946,9 +946,10 @@ impl<'a> TryFrom<&'a CStr> for CString {
type Error = AllocError;
fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
- let mut buf = KVec::new();
+ let bytes = cstr.to_bytes_with_nul();
- buf.extend_from_slice(cstr.to_bytes_with_nul(), GFP_KERNEL)?;
+ let mut buf = KVec::with_capacity(bytes.len(), GFP_KERNEL)?;
+ buf.extend_from_slice(bytes, GFP_KERNEL)?;
// INVARIANT: The `CStr` and `CString` types have the same invariants for
// the string data, and we copied it over without changes.
--
2.51.0
Powered by blists - more mailing lists