Skip to contentSkip to conversation

rust: str: improve safety comment for CString::try_from_fmt

PATCH Applied Nakamura Shuta 3 participants 3 messages Jan 19 – Mar 22 Rust

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 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

---
 rust/kernel/str.rs | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
rust/kernel/str.rs +4 -1
index fa87779d2253..d1fb79c38282 100644
@@ -828,7 +828,10 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
         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.
Signature · 1 line
2.51.0
reviewer Reviewed-by on v1 1/1
#1 lore raw
Quoted 11 lines · Nakamura Shuta

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

Quoted 4 lines
Applied
#2 lore raw
In reply to Nakamura Shuta
Quoted 11 lines · Nakamura Shuta

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

Quoted 4 lines

Applied to rust-next -- thanks everyone!

[ Updated tags: it was a suggestion from Gary from the mailing list
(the linked issue is mostly about adding a debug_assert_eq!).
- Miguel ]

Cheers,
Miguel