Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add is_empty() method to core::ffi::CStr. #102445

Merged
merged 1 commit into from
Oct 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down