Skip to content

Commit

Permalink
Implement CStr::count_bytes
Browse files Browse the repository at this point in the history
This is feature gated under `cstr_count_bytes` and provides a more
straightforward way to access the length of a `CStr`

Link: #113219
  • Loading branch information
tgross35 committed Aug 29, 2023
1 parent e8f9d1a commit fe0eb8b
Showing 1 changed file with 28 additions and 0 deletions.
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 @@ -491,6 +491,34 @@ impl CStr {
self.inner.as_ptr()
}

/// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
///
/// > **Note**: This method is currently implemented as a constant-time
/// > cast, but it is planned to alter its definition in the future to
/// > perform the length calculation whenever this method is called.
///
/// # Examples
///
/// ```
/// #![feature(cstr_count_bytes)]
///
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
/// assert_eq!(cstr.count_bytes(), 3);
///
/// let cstr = CStr::from_bytes_with_nul(b"\0").unwrap();
/// assert_eq!(cstr.count_bytes(), 0);
/// ```
#[inline]
#[must_use]
#[doc(alias("len", "strlen"))]
#[unstable(feature = "cstr_count_bytes", issue = "114441")]
#[rustc_const_unstable(feature = "const_cstr_from_ptr", issue = "113219")]
pub const fn count_bytes(&self) -> usize {
self.inner.len() - 1
}

/// Returns `true` if `self.to_bytes()` has a length of 0.
///
/// # Examples
Expand Down

0 comments on commit fe0eb8b

Please sign in to comment.