Skip to content

Commit 3280db4

Browse files
committed
Remove Eq trait bound
The `PartialOrd` trait is object safe but `Ord` is not. We can make `ArbitraryOrd` object safe by softening the bounds and only requiring `PartialEq` - we still provide a blanket implementation of `Ord` if `Eq` is implemented for `T`. Add a unit test that verifies using `Box<dyn T>` - props to Poelstra for the idea.
1 parent 6a5b6f8 commit 3280db4

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/lib.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ use core::ops::{Deref, DerefMut};
8282
/// }
8383
/// }
8484
/// ```
85-
pub trait ArbitraryOrd<Rhs = Self>: Eq + PartialEq<Rhs> {
85+
pub trait ArbitraryOrd<Rhs = Self>: PartialEq<Rhs> {
8686
/// Implements a meaningless, arbitrary ordering.
8787
fn arbitrary_cmp(&self, other: &Rhs) -> Ordering;
8888
}
@@ -154,11 +154,11 @@ impl<T: ArbitraryOrd> ArbitraryOrd for &T {
154154
}
155155

156156
impl<T: ArbitraryOrd> PartialOrd for Ordered<T> {
157-
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
157+
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some((*self).arbitrary_cmp(other)) }
158158
}
159159

160-
impl<T: ArbitraryOrd> Ord for Ordered<T> {
161-
fn cmp(&self, other: &Self) -> Ordering { self.0.arbitrary_cmp(&other.0) }
160+
impl<T: ArbitraryOrd + Eq> Ord for Ordered<T> {
161+
fn cmp(&self, other: &Self) -> Ordering { (*self).arbitrary_cmp(other) }
162162
}
163163

164164
impl<T: fmt::Display> fmt::Display for Ordered<T> {
@@ -260,4 +260,17 @@ mod tests {
260260
assert_send::<Ordered<Point>>();
261261
assert_sync::<Ordered<Point>>();
262262
}
263+
264+
#[test]
265+
fn trait_is_object_safe() {
266+
extern crate std;
267+
use std::boxed::Box;
268+
269+
// If this test builds then `ArbitraryOrd` is object safe.
270+
#[allow(dead_code)]
271+
struct ObjectSafe {
272+
p: Box<dyn ArbitraryOrd<Self>>,
273+
q: Box<dyn PartialOrd<Self>>, // Sanity check.
274+
}
275+
}
263276
}

0 commit comments

Comments
 (0)