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

impl Send + Sync and override count for the CStr::bytes iterator #127444

Merged
merged 1 commit into from
Jul 17, 2024
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
17 changes: 15 additions & 2 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,8 +780,15 @@ const unsafe fn const_strlen(ptr: *const c_char) -> usize {
pub struct Bytes<'a> {
// since we know the string is nul-terminated, we only need one pointer
ptr: NonNull<u8>,
phantom: PhantomData<&'a u8>,
phantom: PhantomData<&'a [c_char]>,
Sky9x marked this conversation as resolved.
Show resolved Hide resolved
}

#[unstable(feature = "cstr_bytes", issue = "112115")]
unsafe impl Send for Bytes<'_> {}

#[unstable(feature = "cstr_bytes", issue = "112115")]
unsafe impl Sync for Bytes<'_> {}

impl<'a> Bytes<'a> {
#[inline]
fn new(s: &'a CStr) -> Self {
Expand Down Expand Up @@ -814,7 +821,7 @@ impl Iterator for Bytes<'_> {
if ret == 0 {
None
} else {
self.ptr = self.ptr.offset(1);
self.ptr = self.ptr.add(1);
Some(ret)
}
}
Expand All @@ -824,6 +831,12 @@ impl Iterator for Bytes<'_> {
fn size_hint(&self) -> (usize, Option<usize>) {
if self.is_empty() { (0, Some(0)) } else { (1, None) }
}

#[inline]
fn count(self) -> usize {
// SAFETY: We always hold a valid pointer to a C string
unsafe { strlen(self.ptr.as_ptr().cast()) }
}
}

#[unstable(feature = "cstr_bytes", issue = "112115")]
Expand Down
Loading