Skip to content

Commit c82b757

Browse files
authored
Merge pull request #343 from nbdd0121/warnings
Fix warnings in str.rs and binding_generated.rs
2 parents f9dc4fc + 14f1c7c commit c82b757

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

rust/kernel/str.rs

+10-6
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

@@ -188,11 +193,10 @@ impl Index<ops::RangeFrom<usize>> for CStr {
188193
type Output = CStr;
189194

190195
#[inline]
191-
// Clippy false positive
192-
#[allow(clippy::unnecessary_operation)]
193196
fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
194197
// Delegate bounds checking to slice.
195-
&self.as_bytes()[index.start..];
198+
// Assign to _ to mute clippy's unnecessary operation warning.
199+
let _ = &self.as_bytes()[index.start..];
196200
// SAFETY: We just checked the bounds.
197201
unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
198202
}

0 commit comments

Comments
 (0)