about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2022-10-11 18:59:48 +0200
committerGitHub <noreply@github.com>2022-10-11 18:59:48 +0200
commitd10b47ef69a36590a04c76e8868093d251adfec6 (patch)
treee8f0e99fcbe92879815ce826302a0ace11b04232
parent51320b3a16d2fd3e153b122a38ad04ae8ef92963 (diff)
parent9d5e3a1f45a1f62e9826208b922cccf064d619c1 (diff)
downloadrust-d10b47ef69a36590a04c76e8868093d251adfec6.tar.gz
rust-d10b47ef69a36590a04c76e8868093d251adfec6.zip
Rollup merge of #102445 - jmillikin:cstr-is-empty, r=Mark-Simulacrum
Add `is_empty()` method to `core::ffi::CStr`.

ACP: https://github.com/rust-lang/libs-team/issues/106

Tracking issue: https://github.com/rust-lang/rust/issues/102444
-rw-r--r--library/core/src/ffi/c_str.rs28
1 files changed, 28 insertions, 0 deletions
diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs
index 21f80ec025a..55e58c4e0ba 100644
--- a/library/core/src/ffi/c_str.rs
+++ b/library/core/src/ffi/c_str.rs
@@ -474,6 +474,34 @@ impl CStr {
         self.inner.as_ptr()
     }
 
+    /// Returns `true` if `self.to_bytes()` has a length of 0.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(cstr_is_empty)]
+    ///
+    /// use std::ffi::CStr;
+    /// # use std::ffi::FromBytesWithNulError;
+    ///
+    /// # fn main() { test().unwrap(); }
+    /// # fn test() -> Result<(), FromBytesWithNulError> {
+    /// let cstr = CStr::from_bytes_with_nul(b"foo\0")?;
+    /// assert!(!cstr.is_empty());
+    ///
+    /// let empty_cstr = CStr::from_bytes_with_nul(b"\0")?;
+    /// assert!(empty_cstr.is_empty());
+    /// # Ok(())
+    /// # }
+    /// ```
+    #[inline]
+    #[unstable(feature = "cstr_is_empty", issue = "102444")]
+    pub const fn is_empty(&self) -> bool {
+        // SAFETY: We know there is at least one byte; for empty strings it
+        // is the NUL terminator.
+        (unsafe { self.inner.get_unchecked(0) }) == &0
+    }
+
     /// Converts this C string to a byte slice.
     ///
     /// The returned slice will **not** contain the trailing nul terminator that this C