File tree 1 file changed +8
-3
lines changed
1 file changed +8
-3
lines changed Original file line number Diff line number Diff line change @@ -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
You can’t perform that action at this time.
0 commit comments