@@ -89,10 +89,14 @@ impl CStr {
89
89
/// must not be mutated.
90
90
#[ inline]
91
91
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.
92
94
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) }
96
100
}
97
101
98
102
/// Creates a [`CStr`] from a `[u8]`.
@@ -146,6 +150,7 @@ impl CStr {
146
150
// requires `ptr_metadata`).
147
151
// While none of them are current stable, it is very likely that one of
148
152
// them will eventually be.
153
+ // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
149
154
unsafe { & * ( bytes as * const [ u8 ] as * const Self ) }
150
155
}
151
156
@@ -188,11 +193,10 @@ impl Index<ops::RangeFrom<usize>> for CStr {
188
193
type Output = CStr ;
189
194
190
195
#[ inline]
191
- // Clippy false positive
192
- #[ allow( clippy:: unnecessary_operation) ]
193
196
fn index ( & self , index : ops:: RangeFrom < usize > ) -> & Self :: Output {
194
197
// 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 ..] ;
196
200
// SAFETY: We just checked the bounds.
197
201
unsafe { Self :: from_bytes_with_nul_unchecked ( & self . 0 [ index. start ..] ) }
198
202
}
0 commit comments