Skip to content

Commit 7fe44f7

Browse files
authored
Rollup merge of rust-lang#37761 - christophebiocca:borrow-stdlib-fn-refactor, r=alexcrichton
Use Borrow for binary_search and contains methods in the standard library Fixes all standard library methods in rust-lang#32822 that can be fixed without backwards compatibility issues.
2 parents 94ae2a2 + c470d4a commit 7fe44f7

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/libcore/slice.rs

Lines changed: 13 additions & 9 deletions
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;
@@ -100,15 +101,17 @@ pub trait SliceExt {
100101
#[stable(feature = "core", since = "1.6.0")]
101102
fn as_ptr(&self) -> *const Self::Item;
102103
#[stable(feature = "core", since = "1.6.0")]
103-
fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
104-
where Self::Item: Ord;
104+
fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
105+
where Self::Item: Borrow<Q>,
106+
Q: Ord;
105107
#[stable(feature = "core", since = "1.6.0")]
106108
fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
107109
where F: FnMut(&'a Self::Item) -> Ordering;
108110
#[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
109-
fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
111+
fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result<usize, usize>
110112
where F: FnMut(&'a Self::Item) -> B,
111-
B: Ord;
113+
B: Borrow<Q>,
114+
Q: Ord;
112115
#[stable(feature = "core", since = "1.6.0")]
113116
fn len(&self) -> usize;
114117
#[stable(feature = "core", since = "1.6.0")]
@@ -493,8 +496,8 @@ impl<T> SliceExt for [T] {
493496
m >= n && needle == &self[m-n..]
494497
}
495498

496-
fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
497-
self.binary_search_by(|p| p.cmp(x))
499+
fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize> where T: Borrow<Q>, Q: Ord {
500+
self.binary_search_by(|p| p.borrow().cmp(x))
498501
}
499502

500503
#[inline]
@@ -522,11 +525,12 @@ impl<T> SliceExt for [T] {
522525
}
523526

524527
#[inline]
525-
fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
528+
fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
526529
where F: FnMut(&'a Self::Item) -> B,
527-
B: Ord
530+
B: Borrow<Q>,
531+
Q: Ord
528532
{
529-
self.binary_search_by(|k| f(k).cmp(b))
533+
self.binary_search_by(|k| f(k).borrow().cmp(b))
530534
}
531535
}
532536

0 commit comments

Comments
 (0)