Skip to content

Commit d198b85

Browse files
committed
introduce Comparable and Equivalent traits to core under feature flag
1 parent 41f2b6b commit d198b85

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

library/core/src/cmp.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1510,6 +1510,54 @@ pub macro PartialOrd($item:item) {
15101510
/* compiler built-in */
15111511
}
15121512

1513+
/// Key equivalence trait.
1514+
///
1515+
/// This trait allows hash table lookup to be customized.
1516+
///
1517+
/// # Contract
1518+
///
1519+
/// The implementor **must** hash like `Q`, if it is hashable.
1520+
#[unstable(feature = "comparable_trait", issue = "145986")]
1521+
pub trait Equivalent<Q: ?Sized> {
1522+
/// Compare self to `key` and return `true` if they are equal.
1523+
#[unstable(feature = "comparable_trait", issue = "145986")]
1524+
fn equivalent(&self, key: &Q) -> bool;
1525+
}
1526+
1527+
#[unstable(feature = "comparable_trait", issue = "145986")]
1528+
impl<K: ?Sized, Q: ?Sized> Equivalent<Q> for K
1529+
where
1530+
K: crate::borrow::Borrow<Q>,
1531+
Q: Eq,
1532+
{
1533+
#[inline]
1534+
fn equivalent(&self, key: &Q) -> bool {
1535+
PartialEq::eq(self.borrow(), key)
1536+
}
1537+
}
1538+
1539+
/// Key ordering trait.
1540+
///
1541+
/// This trait allows ordered map lookup to be customized.
1542+
#[unstable(feature = "comparable_trait", issue = "145986")]
1543+
pub trait Comparable<Q: ?Sized>: Equivalent<Q> {
1544+
/// Compare self to `key` and return their ordering.
1545+
#[unstable(feature = "comparable_trait", issue = "145986")]
1546+
fn compare(&self, key: &Q) -> Ordering;
1547+
}
1548+
1549+
#[unstable(feature = "comparable_trait", issue = "145986")]
1550+
impl<K: ?Sized, Q: ?Sized> Comparable<Q> for K
1551+
where
1552+
K: crate::borrow::Borrow<Q>,
1553+
Q: Ord,
1554+
{
1555+
#[inline]
1556+
fn compare(&self, key: &Q) -> Ordering {
1557+
Ord::cmp(self.borrow(), key)
1558+
}
1559+
}
1560+
15131561
/// Compares and returns the minimum of two values.
15141562
///
15151563
/// Returns the first argument if the comparison determines them to be equal.

0 commit comments

Comments
 (0)