@@ -507,6 +507,13 @@ impl CStr {
507507 self . inner . as_ptr ( )
508508 }
509509
510+ /// We could eventually expose this publicly, if we wanted.
511+ #[ inline]
512+ #[ must_use]
513+ const fn as_non_null_ptr ( & self ) -> NonNull < c_char > {
514+ NonNull :: from ( & self . inner ) . as_non_null_ptr ( )
515+ }
516+
510517 /// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
511518 ///
512519 /// > **Note**: This method is currently implemented as a constant-time
@@ -776,20 +783,15 @@ pub struct Bytes<'a> {
776783impl < ' a > Bytes < ' a > {
777784 #[ inline]
778785 fn new ( s : & ' a CStr ) -> Self {
779- Self {
780- // SAFETY: Because we have a valid reference to the string, we know
781- // that its pointer is non-null.
782- ptr : unsafe { NonNull :: new_unchecked ( s. as_ptr ( ) as * const u8 as * mut u8 ) } ,
783- phantom : PhantomData ,
784- }
786+ Self { ptr : s. as_non_null_ptr ( ) . cast ( ) , phantom : PhantomData }
785787 }
786788
787789 #[ inline]
788790 fn is_empty ( & self ) -> bool {
789791 // SAFETY: We uphold that the pointer is always valid to dereference
790792 // by starting with a valid C string and then never incrementing beyond
791793 // the nul terminator.
792- unsafe { * self . ptr . as_ref ( ) == 0 }
794+ unsafe { self . ptr . read ( ) == 0 }
793795 }
794796}
795797
@@ -806,11 +808,11 @@ impl Iterator for Bytes<'_> {
806808 // it and assume that adding 1 will create a new, non-null, valid
807809 // pointer.
808810 unsafe {
809- let ret = * self . ptr . as_ref ( ) ;
811+ let ret = self . ptr . read ( ) ;
810812 if ret == 0 {
811813 None
812814 } else {
813- self . ptr = NonNull :: new_unchecked ( self . ptr . as_ptr ( ) . offset ( 1 ) ) ;
815+ self . ptr = self . ptr . offset ( 1 ) ;
814816 Some ( ret)
815817 }
816818 }
0 commit comments