Skip to content

Commit d10b47e

Browse files
authored
Rollup merge of #102445 - jmillikin:cstr-is-empty, r=Mark-Simulacrum
Add `is_empty()` method to `core::ffi::CStr`. ACP: rust-lang/libs-team#106 Tracking issue: #102444
2 parents 51320b3 + 9d5e3a1 commit d10b47e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

library/core/src/ffi/c_str.rs

+28
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,34 @@ impl CStr {
474474
self.inner.as_ptr()
475475
}
476476

477+
/// Returns `true` if `self.to_bytes()` has a length of 0.
478+
///
479+
/// # Examples
480+
///
481+
/// ```
482+
/// #![feature(cstr_is_empty)]
483+
///
484+
/// use std::ffi::CStr;
485+
/// # use std::ffi::FromBytesWithNulError;
486+
///
487+
/// # fn main() { test().unwrap(); }
488+
/// # fn test() -> Result<(), FromBytesWithNulError> {
489+
/// let cstr = CStr::from_bytes_with_nul(b"foo\0")?;
490+
/// assert!(!cstr.is_empty());
491+
///
492+
/// let empty_cstr = CStr::from_bytes_with_nul(b"\0")?;
493+
/// assert!(empty_cstr.is_empty());
494+
/// # Ok(())
495+
/// # }
496+
/// ```
497+
#[inline]
498+
#[unstable(feature = "cstr_is_empty", issue = "102444")]
499+
pub const fn is_empty(&self) -> bool {
500+
// SAFETY: We know there is at least one byte; for empty strings it
501+
// is the NUL terminator.
502+
(unsafe { self.inner.get_unchecked(0) }) == &0
503+
}
504+
477505
/// Converts this C string to a byte slice.
478506
///
479507
/// The returned slice will **not** contain the trailing nul terminator that this C

0 commit comments

Comments
 (0)