range-cmp 1.0.0

Trait that allows comparing a value to a range of values
Documentation
  • Coverage
  • 100%
    20 out of 20 items documented5 out of 11 items with examples
  • Size
  • Source code size: 52.12 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 412.79 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 8s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Akvize/range-cmp
    2 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • qsantos adriendellagaspera romain-akvize

range-cmp

Crates.io MIT licensed Apache licensed Build Status

Docs

This Rust 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);

The crate is #![no_std] and has zero dependencies, so it can be used in embedded and other environments without the standard library. Its MSRV (minimum supported Rust version) is 1.35.

Empty ranges handling

Empty ranges are handled explicitly, instead of returning an arbitrary, representation-dependent answer. An empty range is reported as RangeOrdering::Empty:

use range_cmp::{RangeOrd, RangeOrdering};
assert_eq!(30.rcmp(45..35), RangeOrdering::Empty);
assert_eq!(30.rcmp(25..15), 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 a poset rather than a line, a value may be incomparable with one or both bounds, so a single Below/Inside/Above verdict is not always meaningful. partial_rcmp therefore returns a RangePosition: the pair of the value's relationships to the lower and upper bounds, which never loses information. Use RangePosition::ordering to collapse it into a simple RangeOrdering when the value is comparable with both bounds.

use range_cmp::{PartialRangeOrd, RangeOrdering};
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:
assert_eq!(f64::NAN.partial_rcmp(2.0..3.0).ordering(), None);