fmt_cmp/traits/
fmt_ord.rs

1use std::borrow::Borrow;
2use std::convert::Infallible;
3use std::fmt::Display;
4use std::ops::Deref;
5use std::pin::Pin;
6
7use super::FmtEq;
8
9/// A marker trait for types whose ordering is the same as ordering between its `Display`
10/// representation.
11///
12/// When `T` implements `FmtOrd`, the following property must be upheld for all `a: T` and `b: T`:
13///
14/// ```
15/// # let (a, b) = ("", "");
16/// assert_eq!(a.cmp(&b), (*format!("{}", a)).cmp(&format!("{}", b)));
17/// ```
18///
19/// In other words (assuming that no ill-defined specialization is involved):
20///
21/// ```text
22/// a ⋛ b <-> a.to_string() ⋛ b.to_string()
23/// ```
24///
25/// ## Colloraries
26///
27/// From `str: Ord` and the above property, it follows that `T` satisfies [`Ord`](std::cmp::Ord)
28/// trait's contract.
29///
30/// ## Examples
31///
32/// Integer primitives do not satisfy the property.
33///
34/// ```
35/// assert!(42 < 240);
36/// // but...
37/// assert!(42.to_string() > 240.to_string());
38/// ```
39///
40/// Wrapping any `Display` type with [`fmt_cmp::Cmp`](crate::Cmp) makes it `FmtOrd`:
41///
42/// ```
43/// assert!(fmt_cmp::Cmp(42) > fmt_cmp::Cmp(240));
44/// ```
45pub trait FmtOrd: Display + Ord + FmtEq {}
46
47// Blanket impls for `#[fundamental]` pointer types.
48impl<T: FmtOrd + ?Sized> FmtOrd for &T {}
49impl<T: FmtOrd + ?Sized> FmtOrd for &mut T {}
50impl<P: Borrow<<P as Deref>::Target> + Deref + Display> FmtOrd for Pin<P> where P::Target: FmtOrd {}
51
52impl FmtOrd for str {}
53// Both `false < true` and `"false" < "true"` hold coincidentally.
54impl FmtOrd for bool {}
55
56impl FmtOrd for Infallible {}
57
58// `alloc` types.
59#[cfg(feature = "alloc")]
60impl<T: FmtOrd + ?Sized> FmtOrd for alloc::boxed::Box<T> {}
61#[cfg(feature = "alloc")]
62impl<T: FmtOrd + ?Sized> FmtOrd for alloc::rc::Rc<T> {}
63#[cfg(feature = "alloc")]
64impl<T: FmtOrd + ?Sized> FmtOrd for alloc::sync::Arc<T> {}
65#[cfg(feature = "alloc")]
66impl<T: FmtOrd + alloc::borrow::ToOwned + ?Sized> FmtOrd for alloc::borrow::Cow<'_, T> where
67    T::Owned: Display
68{
69}
70#[cfg(feature = "alloc")]
71impl FmtOrd for alloc::string::String {}