@@ -4018,6 +4018,55 @@ impl<T> [T] {
4018
4018
* self = rem;
4019
4019
Some ( last)
4020
4020
}
4021
+
4022
+ /// Gives the `Range` where the `other` slice is located within `self`,
4023
+ /// or `None` if it is not a sub-slice.
4024
+ ///
4025
+ /// This method can be thought of as the opposite of [`get`](#method.get),
4026
+ /// and they mutually guarantee slice-to-slice roundtrips, as well as
4027
+ /// range-to-range roundtrips if `T` is not a Zero-Sized Type.
4028
+ ///
4029
+ /// This means that the resulting [`Range`] can be passed to
4030
+ /// [`get`](#method.get) and will always return a slice that is [`ptr::eq`]
4031
+ /// to the one passed to this function.
4032
+ ///
4033
+ /// If `T` is a Zero-Sized Type ("ZST"), the resulting [`Range`] will always
4034
+ /// start at `0`, and thus range-to-range roundtrips are not guaranteed.
4035
+ ///
4036
+ /// # Examples
4037
+ ///
4038
+ /// ```
4039
+ /// #![feature(slice_range_of)]
4040
+ ///
4041
+ /// let slice: &[u8] = &[1, 2, 3, 4, 5];
4042
+ /// let subslice = &slice[1..3];
4043
+ /// let foreign_slice: &[u8] = &[2, 3];
4044
+ ///
4045
+ /// assert_eq!(slice.range_of(subslice), Some(1..3));
4046
+ /// assert_eq!(slice.range_of(foreign_slice), None);
4047
+ /// ```
4048
+ #[ unstable( feature = "slice_range_of" , issue = "none" ) ]
4049
+ #[ inline]
4050
+ pub fn range_of ( & self , other : & Self ) -> Option < Range < usize > > {
4051
+ if mem:: size_of :: < T > ( ) == 0 {
4052
+ return if self . as_ptr ( ) == other. as_ptr ( ) && self . len ( ) <= other. len ( ) {
4053
+ Some ( 0 ..self . len ( ) )
4054
+ } else {
4055
+ None
4056
+ } ;
4057
+ }
4058
+
4059
+ let self_ptr = self . as_ptr_range ( ) ;
4060
+ let other_ptr = other. as_ptr_range ( ) ;
4061
+ if self_ptr. start <= other_ptr. start && other_ptr. end <= self_ptr. end {
4062
+ // SAFETY: the bounds checks above uphold the safety contract for `sub_ptr`.
4063
+ Some ( unsafe {
4064
+ other_ptr. start . sub_ptr ( self_ptr. start ) ..other_ptr. end . sub_ptr ( self_ptr. start )
4065
+ } )
4066
+ } else {
4067
+ None
4068
+ }
4069
+ }
4021
4070
}
4022
4071
4023
4072
impl < T , const N : usize > [ [ T ; N ] ] {
0 commit comments