rust-range-check
This is a little library that helps with range and bounds checking. It works with Rust’s standard Range
, RangeFrom
, and RangeTo
types.
View the Rustdoc
Installation
This crate works with Cargo. Add the following to your Cargo.toml
dependencies section:
[]
= "0.1"
Checking whether a range contains a value
The trait Contains
is implemented on the range types. As long as the data type in question is PartialOrd
, it can be used to check whether a value of that type is contained within a range:
use Contains;
let range = 3000..5000;
assert!;
let range = 10..;
assert!;
There’s also the Within
trait, which does the same check, only with the range as the argument:
use Within;
assert!;
assert!;
Failing early if a value is outside a range
It can sometimes be more helpful to automatically return a failure case, such as with the try!
macro, than just check whether a value is inside a range. The Check
trait returns Result
s that contain debugging information for when a value doesn’t lie within a range:
use Check;
assert!;
assert!;
Displaying the Error
that gets returned in the error case shows you exactly which range failed to be satisfied:
use ToString;
use Check;
let failure = 13.check_range.unwrap_err;
assert_eq!;