@@ -741,6 +741,44 @@ impl<T> [T] {
741741 core_slice:: SliceExt :: binary_search_by ( self , f)
742742 }
743743
744+ /// Binary search a sorted slice with a key extraction function.
745+ ///
746+ /// Assumes that the slice is sorted by the key, for instance with
747+ /// `sort_by_key` using the same key extraction function.
748+ ///
749+ /// If a matching value is found then returns `Ok`, containing the
750+ /// index for the matched element; if no match is found then `Err`
751+ /// is returned, containing the index where a matching element could
752+ /// be inserted while maintaining sorted order.
753+ ///
754+ /// # Examples
755+ ///
756+ /// Looks up a series of four elements in a slice of pairs sorted by
757+ /// their second elements. The first is found, with a uniquely
758+ /// determined position; the second and third are not found; the
759+ /// fourth could match any position in `[1,4]`.
760+ ///
761+ /// ```rust
762+ /// #![feature(slice_binary_search_by_key)]
763+ /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
764+ /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
765+ /// (1, 21), (2, 34), (4, 55)];
766+ ///
767+ /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
768+ /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
769+ /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
770+ /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
771+ /// assert!(match r { Ok(1...4) => true, _ => false, });
772+ /// ```
773+ #[ unstable( feature = "slice_binary_search_by_key" , reason = "recently added" , issue = "0" ) ]
774+ #[ inline]
775+ pub fn binary_search_by_key < B , F > ( & self , b : & B , f : F ) -> Result < usize , usize >
776+ where F : FnMut ( & T ) -> B ,
777+ B : Ord
778+ {
779+ core_slice:: SliceExt :: binary_search_by_key ( self , b, f)
780+ }
781+
744782 /// Sorts the slice, in place.
745783 ///
746784 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
0 commit comments