From c470d4a415fe6f091170cf7e55926e252252d0f9 Mon Sep 17 00:00:00 2001 From: Christophe Biocca Date: Sun, 13 Nov 2016 21:55:41 -0500 Subject: [PATCH] Add borrow support for slice binary search methods. --- src/libcore/slice.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 871b63145ca6..d716be26139d 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -33,6 +33,7 @@ // * The `raw` and `bytes` submodules. // * Boilerplate trait implementations. +use borrow::Borrow; use cmp::Ordering::{self, Less, Equal, Greater}; use cmp; use fmt; @@ -94,15 +95,17 @@ pub trait SliceExt { #[stable(feature = "core", since = "1.6.0")] fn as_ptr(&self) -> *const Self::Item; #[stable(feature = "core", since = "1.6.0")] - fn binary_search(&self, x: &Self::Item) -> Result - where Self::Item: Ord; + fn binary_search(&self, x: &Q) -> Result + where Self::Item: Borrow, + Q: Ord; #[stable(feature = "core", since = "1.6.0")] fn binary_search_by<'a, F>(&'a self, f: F) -> Result where F: FnMut(&'a Self::Item) -> Ordering; #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")] - fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result + fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result where F: FnMut(&'a Self::Item) -> B, - B: Ord; + B: Borrow, + Q: Ord; #[stable(feature = "core", since = "1.6.0")] fn len(&self) -> usize; #[stable(feature = "core", since = "1.6.0")] @@ -477,8 +480,8 @@ impl SliceExt for [T] { m >= n && needle == &self[m-n..] } - fn binary_search(&self, x: &T) -> Result where T: Ord { - self.binary_search_by(|p| p.cmp(x)) + fn binary_search(&self, x: &Q) -> Result where T: Borrow, Q: Ord { + self.binary_search_by(|p| p.borrow().cmp(x)) } #[inline] @@ -506,11 +509,12 @@ impl SliceExt for [T] { } #[inline] - fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result + fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result where F: FnMut(&'a Self::Item) -> B, - B: Ord + B: Borrow, + Q: Ord { - self.binary_search_by(|k| f(k).cmp(b)) + self.binary_search_by(|k| f(k).borrow().cmp(b)) } }