Skip to content

Commit c470d4a

Browse files
Add borrow support for slice binary search methods.
1 parent fb025b4 commit c470d4a

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/libcore/slice.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
// * The `raw` and `bytes` submodules.
3434
// * Boilerplate trait implementations.
3535

36+
use borrow::Borrow;
3637
use cmp::Ordering::{self, Less, Equal, Greater};
3738
use cmp;
3839
use fmt;
@@ -94,15 +95,17 @@ pub trait SliceExt {
9495
#[stable(feature = "core", since = "1.6.0")]
9596
fn as_ptr(&self) -> *const Self::Item;
9697
#[stable(feature = "core", since = "1.6.0")]
97-
fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
98-
where Self::Item: Ord;
98+
fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
99+
where Self::Item: Borrow<Q>,
100+
Q: Ord;
99101
#[stable(feature = "core", since = "1.6.0")]
100102
fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
101103
where F: FnMut(&'a Self::Item) -> Ordering;
102104
#[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
103-
fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
105+
fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result<usize, usize>
104106
where F: FnMut(&'a Self::Item) -> B,
105-
B: Ord;
107+
B: Borrow<Q>,
108+
Q: Ord;
106109
#[stable(feature = "core", since = "1.6.0")]
107110
fn len(&self) -> usize;
108111
#[stable(feature = "core", since = "1.6.0")]
@@ -477,8 +480,8 @@ impl<T> SliceExt for [T] {
477480
m >= n && needle == &self[m-n..]
478481
}
479482

480-
fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
481-
self.binary_search_by(|p| p.cmp(x))
483+
fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize> where T: Borrow<Q>, Q: Ord {
484+
self.binary_search_by(|p| p.borrow().cmp(x))
482485
}
483486

484487
#[inline]
@@ -506,11 +509,12 @@ impl<T> SliceExt for [T] {
506509
}
507510

508511
#[inline]
509-
fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
512+
fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
510513
where F: FnMut(&'a Self::Item) -> B,
511-
B: Ord
514+
B: Borrow<Q>,
515+
Q: Ord
512516
{
513-
self.binary_search_by(|k| f(k).cmp(b))
517+
self.binary_search_by(|k| f(k).borrow().cmp(b))
514518
}
515519
}
516520

0 commit comments

Comments
 (0)