Skip to content

Commit 6a00a41

Browse files
committed
rust: add safety annotations to str.rs
Signed-off-by: Gary Guo <[email protected]>
1 parent cae4454 commit 6a00a41

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

rust/kernel/str.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,14 @@ impl CStr {
8989
/// must not be mutated.
9090
#[inline]
9191
pub unsafe fn from_char_ptr<'a>(ptr: *const c_types::c_char) -> &'a Self {
92+
// SAFETY: The safety precondition guarantees `ptr` is a valid pointer
93+
// to a `NUL`-terminated C string.
9294
let len = unsafe { bindings::strlen(ptr) } + 1;
93-
unsafe {
94-
Self::from_bytes_with_nul_unchecked(core::slice::from_raw_parts(ptr as _, len as _))
95-
}
95+
// SAFETY: lifetime guaranteed by the safety precondition.
96+
let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
97+
// SAFETY: as `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
98+
// As we have added 1 to `len`, the last byte is known to be `NUL`.
99+
unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
96100
}
97101

98102
/// Creates a [`CStr`] from a `[u8]`.
@@ -146,6 +150,7 @@ impl CStr {
146150
// requires `ptr_metadata`).
147151
// While none of them are current stable, it is very likely that one of
148152
// them will eventually be.
153+
// SAFETY: properties of `bytes` guaranteed by the safety precondition.
149154
unsafe { &*(bytes as *const [u8] as *const Self) }
150155
}
151156

0 commit comments

Comments
 (0)