@@ -89,8 +89,13 @@ 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
- 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) }
94
99
}
95
100
96
101
/// Creates a [`CStr`] from a `[u8]`.
@@ -144,7 +149,8 @@ impl CStr {
144
149
// requires `ptr_metadata`).
145
150
// While none of them are current stable, it is very likely that one of
146
151
// 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 ) }
148
154
}
149
155
150
156
/// Returns a C pointer to the string.
@@ -186,11 +192,10 @@ impl Index<ops::RangeFrom<usize>> for CStr {
186
192
type Output = CStr ;
187
193
188
194
#[ inline]
189
- // Clippy false positive
190
- #[ allow( clippy:: unnecessary_operation) ]
191
195
fn index ( & self , index : ops:: RangeFrom < usize > ) -> & Self :: Output {
192
196
// 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 ..] ;
194
199
// SAFETY: We just checked the bounds.
195
200
unsafe { Self :: from_bytes_with_nul_unchecked ( & self . 0 [ index. start ..] ) }
196
201
}
0 commit comments