@@ -507,6 +507,13 @@ impl CStr {
507
507
self . inner . as_ptr ( )
508
508
}
509
509
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
+
510
517
/// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
511
518
///
512
519
/// > **Note**: This method is currently implemented as a constant-time
@@ -776,20 +783,15 @@ pub struct Bytes<'a> {
776
783
impl < ' a > Bytes < ' a > {
777
784
#[ inline]
778
785
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 }
785
787
}
786
788
787
789
#[ inline]
788
790
fn is_empty ( & self ) -> bool {
789
791
// SAFETY: We uphold that the pointer is always valid to dereference
790
792
// by starting with a valid C string and then never incrementing beyond
791
793
// the nul terminator.
792
- unsafe { * self . ptr . as_ref ( ) == 0 }
794
+ unsafe { self . ptr . read ( ) == 0 }
793
795
}
794
796
}
795
797
@@ -806,11 +808,11 @@ impl Iterator for Bytes<'_> {
806
808
// it and assume that adding 1 will create a new, non-null, valid
807
809
// pointer.
808
810
unsafe {
809
- let ret = * self . ptr . as_ref ( ) ;
811
+ let ret = self . ptr . read ( ) ;
810
812
if ret == 0 {
811
813
None
812
814
} else {
813
- self . ptr = NonNull :: new_unchecked ( self . ptr . as_ptr ( ) . offset ( 1 ) ) ;
815
+ self . ptr = self . ptr . offset ( 1 ) ;
814
816
Some ( ret)
815
817
}
816
818
}
0 commit comments