Skip to content

Commit fe0eb8b

Browse files
committed
Implement CStr::count_bytes
This is feature gated under `cstr_count_bytes` and provides a more straightforward way to access the length of a `CStr` Link: rust-lang#113219
1 parent e8f9d1a commit fe0eb8b

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
@@ -491,6 +491,34 @@ impl CStr {
491491
self.inner.as_ptr()
492492
}
493493

494+
/// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
495+
///
496+
/// > **Note**: This method is currently implemented as a constant-time
497+
/// > cast, but it is planned to alter its definition in the future to
498+
/// > perform the length calculation whenever this method is called.
499+
///
500+
/// # Examples
501+
///
502+
/// ```
503+
/// #![feature(cstr_count_bytes)]
504+
///
505+
/// use std::ffi::CStr;
506+
///
507+
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
508+
/// assert_eq!(cstr.count_bytes(), 3);
509+
///
510+
/// let cstr = CStr::from_bytes_with_nul(b"\0").unwrap();
511+
/// assert_eq!(cstr.count_bytes(), 0);
512+
/// ```
513+
#[inline]
514+
#[must_use]
515+
#[doc(alias("len", "strlen"))]
516+
#[unstable(feature = "cstr_count_bytes", issue = "114441")]
517+
#[rustc_const_unstable(feature = "const_cstr_from_ptr", issue = "113219")]
518+
pub const fn count_bytes(&self) -> usize {
519+
self.inner.len() - 1
520+
}
521+
494522
/// Returns `true` if `self.to_bytes()` has a length of 0.
495523
///
496524
/// # Examples

0 commit comments

Comments
 (0)