rust: str: improve safety comment for CString::try_from_fmt
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
@@ -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
Quoted 11 lines · Nakamura Shuta
Improve the safety comment for the
inc_len()call inCString::try_from_fmt()to clarify whybytes_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. TheFormatteris created withsizeas its capacity limit
2. The?operators onwrite_fmtandwrite_strensure early return if writing exceeds this limit
Quoted 4 lines
Suggested-by Gary Guo <[email protected]>Reported-by Kane York <[email protected]>Signed-off-by Nakamura Shuta <[email protected]>
Miguel Ojeda
AppliedQuoted 11 lines · Nakamura Shuta
Improve the safety comment for the
inc_len()call inCString::try_from_fmt()to clarify whybytes_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. TheFormatteris created withsizeas its capacity limit
2. The?operators onwrite_fmtandwrite_strensure early return if writing exceeds this limit
Quoted 4 lines
Suggested-by Gary Guo <[email protected]>Reported-by Kane York <[email protected]>Signed-off-by Nakamura Shuta <[email protected]>
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