Skip to content

Commit

Permalink
Rollup merge of rust-lang#127444 - Sky9x:cstr-bytes-iter, r=dtolnay
Browse files Browse the repository at this point in the history
`impl Send + Sync` and override `count` for the `CStr::bytes` iterator

cc tracking issue rust-lang#112115
  • Loading branch information
tgross35 authored Jul 17, 2024
2 parents 12075d1 + 704f56f commit d3cf2e1
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,8 +781,15 @@ const unsafe fn 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]>,
}

#[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 @@ -815,7 +822,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 @@ -825,6 +832,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

0 comments on commit d3cf2e1

Please sign in to comment.