@@ -500,6 +500,44 @@ impl<T: ?Sized> *const T {
500
500
intrinsics:: arith_offset ( self , count)
501
501
}
502
502
}
503
+
504
+ /// Calculates the distance between two pointers. The returned value is in
505
+ /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
506
+ ///
507
+ /// If the address different between the two pointers ia not a multiple of
508
+ /// `mem::size_of::<T>()` then the result of the division is rounded towards
509
+ /// zero.
510
+ ///
511
+ /// This function returns `None` if `T` is a zero-sized typed.
512
+ ///
513
+ /// # Examples
514
+ ///
515
+ /// Basic usage:
516
+ ///
517
+ /// ```
518
+ /// #![feature(offset_to)]
519
+ ///
520
+ /// fn main() {
521
+ /// let a = [0; 5];
522
+ /// let ptr1: *const i32 = &a[1];
523
+ /// let ptr2: *const i32 = &a[3];
524
+ /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
525
+ /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
526
+ /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
527
+ /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
528
+ /// }
529
+ /// ```
530
+ #[ unstable( feature = "offset_to" , issue = "0" ) ]
531
+ #[ inline]
532
+ pub fn offset_to ( self , other : * const T ) -> Option < isize > where T : Sized {
533
+ let size = mem:: size_of :: < T > ( ) ;
534
+ if size == 0 {
535
+ None
536
+ } else {
537
+ let diff = ( other as isize ) . wrapping_sub ( self as isize ) ;
538
+ Some ( diff / size as isize )
539
+ }
540
+ }
503
541
}
504
542
505
543
#[ lang = "mut_ptr" ]
@@ -653,6 +691,44 @@ impl<T: ?Sized> *mut T {
653
691
Some ( & mut * self )
654
692
}
655
693
}
694
+
695
+ /// Calculates the distance between two pointers. The returned value is in
696
+ /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
697
+ ///
698
+ /// If the address different between the two pointers ia not a multiple of
699
+ /// `mem::size_of::<T>()` then the result of the division is rounded towards
700
+ /// zero.
701
+ ///
702
+ /// This function returns `None` if `T` is a zero-sized typed.
703
+ ///
704
+ /// # Examples
705
+ ///
706
+ /// Basic usage:
707
+ ///
708
+ /// ```
709
+ /// #![feature(offset_to)]
710
+ ///
711
+ /// fn main() {
712
+ /// let mut a = [0; 5];
713
+ /// let ptr1: *mut i32 = &mut a[1];
714
+ /// let ptr2: *mut i32 = &mut a[3];
715
+ /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
716
+ /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
717
+ /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
718
+ /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
719
+ /// }
720
+ /// ```
721
+ #[ unstable( feature = "offset_to" , issue = "0" ) ]
722
+ #[ inline]
723
+ pub fn offset_to ( self , other : * const T ) -> Option < isize > where T : Sized {
724
+ let size = mem:: size_of :: < T > ( ) ;
725
+ if size == 0 {
726
+ None
727
+ } else {
728
+ let diff = ( other as isize ) . wrapping_sub ( self as isize ) ;
729
+ Some ( diff / size as isize )
730
+ }
731
+ }
656
732
}
657
733
658
734
// Equality for pointers
0 commit comments