From 84542d22a71cb486b0f79cf3bfd7a264b688030c Mon Sep 17 00:00:00 2001 From: klensy Date: Sun, 28 Mar 2021 19:34:38 +0300 Subject: [PATCH 1/2] ffi::c_str added tests for empty strings --- library/std/src/ffi/c_str/tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/library/std/src/ffi/c_str/tests.rs b/library/std/src/ffi/c_str/tests.rs index 4dff3df63a8b6..4f7ba9ad43756 100644 --- a/library/std/src/ffi/c_str/tests.rs +++ b/library/std/src/ffi/c_str/tests.rs @@ -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()); +} From a0ff4612f21e312362a3ffbec0a104b9937d700b Mon Sep 17 00:00:00 2001 From: klensy Date: Sun, 28 Mar 2021 19:55:09 +0300 Subject: [PATCH 2/2] ffi::c_str smaller as_bytes --- library/std/src/ffi/c_str.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs index 687ed61b95961..ed4950c57a627 100644 --- a/library/std/src/ffi/c_str.rs +++ b/library/std/src/ffi/c_str.rs @@ -613,7 +613,8 @@ impl CString { #[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 @@ impl CStr { #[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.