Auto merge of #83609 - klensy:c-str, r=m-ou-se
ffi::c_str removed bound checks on as_bytes, to_bytes This removes bound checks on CString::as_bytes() and CStr::to_bytes() and adds test.
This commit is contained in:
commit
7750402c5e
@ -613,7 +613,8 @@ pub fn into_bytes_with_nul(self) -> Vec<u8> {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
&self.inner[..self.inner.len() - 1]
|
||||
// SAFETY: CString has a length at least 1
|
||||
unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
|
||||
}
|
||||
|
||||
/// Equivalent to [`CString::as_bytes()`] except that the
|
||||
@ -1322,7 +1323,8 @@ pub const fn as_ptr(&self) -> *const c_char {
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub fn to_bytes(&self) -> &[u8] {
|
||||
let bytes = self.to_bytes_with_nul();
|
||||
&bytes[..bytes.len() - 1]
|
||||
// SAFETY: to_bytes_with_nul returns slice with length at least 1
|
||||
unsafe { bytes.get_unchecked(..bytes.len() - 1) }
|
||||
}
|
||||
|
||||
/// Converts this C string to a byte slice containing the trailing 0 byte.
|
||||
|
@ -193,3 +193,19 @@ fn cstr_index_from_empty() {
|
||||
let cstr = CStr::from_bytes_with_nul(original).unwrap();
|
||||
let _ = &cstr[original.len()..];
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_string_from_empty_string() {
|
||||
let original = "";
|
||||
let cstring = CString::new(original).unwrap();
|
||||
assert_eq!(original.as_bytes(), cstring.as_bytes());
|
||||
assert_eq!([b'\0'], cstring.as_bytes_with_nul());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_str_from_empty_string() {
|
||||
let original = b"\0";
|
||||
let cstr = CStr::from_bytes_with_nul(original).unwrap();
|
||||
assert_eq!([] as [u8; 0], cstr.to_bytes());
|
||||
assert_eq!([b'\0'], cstr.to_bytes_with_nul());
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user