Expand description
This crate provides the RangeOrd trait on all types that implement Ord.
This trait exposes a rcmp associated method that allows
comparing a value with a range of values:
use range_cmp::{RangeOrd, RangeOrdering};
assert_eq!(15.rcmp(20..30), RangeOrdering::Below);
assert_eq!(25.rcmp(20..30), RangeOrdering::Inside);
assert_eq!(35.rcmp(20..30), RangeOrdering::Above);§Empty ranges
Unlike previous versions, the crate now handles empty ranges explicitly, instead
of returning an arbitrary, representation-dependent answer. An empty range (such as
30..20 or 0..0) is reported as RangeOrdering::Empty:
use range_cmp::{RangeOrd, RangeOrdering};
assert_eq!(25.rcmp(30..20), RangeOrdering::Empty);
assert_eq!(0.rcmp(0..0), RangeOrdering::Empty);Emptiness is judged from the bounds, not from the population of the type: ..0u32
is treated as a regular (non-empty) range even though no u32 is below 0.
§Partial orders
The crate also provides the PartialRangeOrd trait on all types that implement
PartialOrd. Because a partial order is not a line but a poset, a value cannot
always be collapsed into a single Below/Inside/Above verdict: it may be
incomparable with one or both bounds. partial_rcmp
therefore returns a RangePosition, the pair of the value’s relationships to the
lower and upper bounds, which never loses information:
use range_cmp::{PartialRangeOrd, RangeOrdering};
// `f64` is `PartialOrd` but not `Ord`.
assert_eq!(1.5_f64.partial_rcmp(2.0..3.0).ordering(), Some(RangeOrdering::Below));
assert_eq!(2.5_f64.partial_rcmp(2.0..3.0).ordering(), Some(RangeOrdering::Inside));
assert_eq!(3.5_f64.partial_rcmp(2.0..3.0).ordering(), Some(RangeOrdering::Above));
// `NaN` is incomparable with the bounds, so there is no single verdict:
assert_eq!(core::f64::NAN.partial_rcmp(2.0..3.0).ordering(), None);§no_std
The crate is #![no_std]: it has no dependencies and only relies on core, so it
can be used in embedded and other environments without the standard library.
Structs§
- Range
Position - Full position of a value relative to a range, expressed as the pair of its relationships to the lower and the upper bound.
Enums§
- Bound
Ordering - Position of a value relative to a single bound of a range.
- Range
Ordering - Simplified result for
RangeOrd::rcmp, obtained for totally ordered types or by collapsing aRangePositionthroughRangePosition::ordering.
Traits§
- Borrow
Range - Helper trait to allow passing a range as either a owned value or a reference.
- Partial
Range Ord - Trait to provide the
partial_rcmpmethod, which allows comparing the type to a range. A blanket implementation is provided for all types that implement thePartialOrdtrait. - Range
Ord - Trait to provide the
rcmpmethod, which allows comparing the type to a range. A blanket implementation is provided for all types that implement theOrdtrait.