Skip to content

Commit 1f1721b

Browse files
committed
rust: fix warnings in str.rs
Signed-off-by: Gary Guo <[email protected]>
1 parent 0b9bcdf commit 1f1721b

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

rust/kernel/str.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,13 @@ 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-
let len = bindings::strlen(ptr) + 1;
93-
Self::from_bytes_with_nul_unchecked(core::slice::from_raw_parts(ptr as _, len as _))
92+
// SAFETY: `ptr` is a valid pointer to a `NUL`-terminated C string.
93+
let len = unsafe { bindings::strlen(ptr) + 1 };
94+
// SAFETY: lifetime guaranteed by the caller.
95+
let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
96+
// SAFETY: as `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
97+
// As we have added 1 to `len`, the last byte is known to be `NUL`.
98+
unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
9499
}
95100

96101
/// Creates a [`CStr`] from a `[u8]`.
@@ -144,7 +149,8 @@ impl CStr {
144149
// requires `ptr_metadata`).
145150
// While none of them are current stable, it is very likely that one of
146151
// them will eventually be.
147-
&*(bytes as *const [u8] as *const Self)
152+
// SAFETY: property of `bytes` guaranteed by the caller.
153+
unsafe { &*(bytes as *const [u8] as *const Self) }
148154
}
149155

150156
/// Returns a C pointer to the string.
@@ -186,11 +192,10 @@ impl Index<ops::RangeFrom<usize>> for CStr {
186192
type Output = CStr;
187193

188194
#[inline]
189-
// Clippy false positive
190-
#[allow(clippy::unnecessary_operation)]
191195
fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
192196
// Delegate bounds checking to slice.
193-
&self.as_bytes()[index.start..];
197+
// Assign to _ to mute clippy's unnecessary operation warning.
198+
let _ = &self.as_bytes()[index.start..];
194199
// SAFETY: We just checked the bounds.
195200
unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
196201
}

0 commit comments

Comments
 (0)