Skip to content

Commit

Permalink
Reduce unsafe code, use more NonNull APIs per @cuviper review
Browse files Browse the repository at this point in the history
  • Loading branch information
clarfonthey committed Mar 12, 2024
1 parent 15b71f4 commit 0a90d2d
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,13 @@ impl CStr {
self.inner.as_ptr()
}

/// We could eventually expose this publicly, if we wanted.
#[inline]
#[must_use]
const fn as_non_null_ptr(&self) -> NonNull<c_char> {
NonNull::from(&self.inner).as_non_null_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
Expand Down Expand Up @@ -776,20 +783,15 @@ pub struct Bytes<'a> {
impl<'a> Bytes<'a> {
#[inline]
fn new(s: &'a CStr) -> Self {
Self {
// SAFETY: Because we have a valid reference to the string, we know
// that its pointer is non-null.
ptr: unsafe { NonNull::new_unchecked(s.as_ptr() as *const u8 as *mut u8) },
phantom: PhantomData,
}
Self { ptr: s.as_non_null_ptr().cast(), phantom: PhantomData }
}

#[inline]
fn is_empty(&self) -> bool {
// SAFETY: We uphold that the pointer is always valid to dereference
// by starting with a valid C string and then never incrementing beyond
// the nul terminator.
unsafe { *self.ptr.as_ref() == 0 }
unsafe { self.ptr.read() == 0 }
}
}

Expand All @@ -805,14 +807,12 @@ impl Iterator for Bytes<'_> {
// the pointer is non-null and valid. This lets us safely dereference
// it and assume that adding 1 will create a new, non-null, valid
// pointer.
unsafe {
let ret = *self.ptr.as_ref();
if ret == 0 {
None
} else {
self.ptr = NonNull::new_unchecked(self.ptr.as_ptr().offset(1));
Some(ret)
}
let ret = unsafe { self.ptr.read() };
if ret == 0 {
None
} else {
self.ptr = self.ptr.offset(1);
Some(ret)
}
}

Expand Down

0 comments on commit 0a90d2d

Please sign in to comment.