about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTrevor Gross <tmgross@umich.edu>2023-08-03 19:38:43 -0400
committerTrevor Gross <tmgross@umich.edu>2023-08-29 13:38:22 -0400
commitfe0eb8b49bd31cb956d15ac61ff6bee5b17f59ed (patch)
tree8434cab68ed920bf956e4f1e69bb8988b994791c
parente8f9d1a80f1e21dd3b4198c35b9596fb62e8786d (diff)
downloadrust-fe0eb8b49bd31cb956d15ac61ff6bee5b17f59ed.tar.gz
rust-fe0eb8b49bd31cb956d15ac61ff6bee5b17f59ed.zip
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: https://github.com/rust-lang/rust/issues/113219
-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 801447e96cd..5592fe8e324 100644
--- a/library/core/src/ffi/c_str.rs
+++ b/library/core/src/ffi/c_str.rs
@@ -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