From bf074eb6891be799174ff42e0051492681fdc045 Mon Sep 17 00:00:00 2001 From: Nakamura Shuta Date: Mon, 19 Jan 2026 15:29:25 +0900 Subject: [PATCH] rust: str: improve safety comment for CString::try_from_fmt Improve the safety comment for the `inc_len()` call in `CString::try_from_fmt()` to clarify why `bytes_written()` is guaranteed not to exceed the buffer capacity. The current comment states that bytes written is bounded by size, but does not explain that this invariant is maintained because: 1. The `Formatter` is created with `size` as its capacity limit 2. The `?` operators on `write_fmt` and `write_str` ensure early return if writing exceeds this limit Suggested-by: Gary Guo Link: https://lore.kernel.org/rust-for-linux/20221114145329.0f47a3ab@GaryWorkstation/ Link: https://github.com/Rust-for-Linux/linux/issues/936 Signed-off-by: Nakamura Shuta Reviewed-by: Alice Ryhl Link: https://patch.msgid.link/20260119062925.1647-1-nakamura.shuta@gmail.com [ Updated tags: it was a suggestion from Gary from the mailing list (the linked issue is mostly about adding a `debug_assert_eq!`). - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 9f547ba068bb4..9b89564ae6d87 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -844,7 +844,10 @@ impl CString { f.write_str("\0")?; // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is - // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`. + // `buf`'s capacity. The `Formatter` is created with `size` as its limit, and the `?` + // operators on `write_fmt` and `write_str` above ensure that if writing exceeds this + // limit, an error is returned early. The contents of the buffer have been initialised + // by writes to `f`. unsafe { buf.inc_len(f.bytes_written()) }; // Check that there are no `NUL` bytes before the end. -- 2.47.3