diff options
| author | Inteon <42113979+inteon@users.noreply.github.com> | 2022-02-06 20:07:03 +0100 |
|---|---|---|
| committer | Inteon <42113979+inteon@users.noreply.github.com> | 2022-02-06 20:07:03 +0100 |
| commit | afb7a502f6e4e564d034ebf9601f4a4a13551f15 (patch) | |
| tree | 9ac982421c63517a5aa0c1c5385e11b730e88111 | |
| parent | f624427f8771c00819684c783bb841bf72095704 (diff) | |
| download | rust-afb7a502f6e4e564d034ebf9601f4a4a13551f15.tar.gz rust-afb7a502f6e4e564d034ebf9601f4a4a13551f15.zip | |
rewrite from_bytes_with_nul to match code style in from_vec_with_nul
Signed-off-by: Inteon <42113979+inteon@users.noreply.github.com>
| -rw-r--r-- | library/std/src/ffi/c_str.rs | 15 |
1 files changed, 8 insertions, 7 deletions
diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs index 66fee2fe548..e10c6a5daf1 100644 --- a/library/std/src/ffi/c_str.rs +++ b/library/std/src/ffi/c_str.rs @@ -1252,15 +1252,16 @@ impl CStr { /// assert!(cstr.is_err()); /// ``` #[stable(feature = "cstr_from_bytes", since = "1.10.0")] - pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> { + pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> { let nul_pos = memchr::memchr(0, bytes); - if let Some(nul_pos) = nul_pos { - if nul_pos + 1 != bytes.len() { - return Err(FromBytesWithNulError::interior_nul(nul_pos)); + match nul_pos { + Some(nul_pos) if nul_pos + 1 == bytes.len() => { + // SAFETY: We know there is only one nul byte, at the end + // of the byte slice. + Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }) } - Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) }) - } else { - Err(FromBytesWithNulError::not_nul_terminated()) + Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)), + None => Err(FromBytesWithNulError::not_nul_terminated()), } } |
