This is a little library that helps with range and bounds checking. It works with Rust’s standard Range
, RangeFrom
, and RangeTo
types.
This crate works with Cargo. Add the following to your Cargo.toml
dependencies section:
toml
[dependencies]
range_check = "0.1"
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:
```rust use range_check::Contains;
let range = 3000..5000; assert!(range.contains(4123));
let range = 10..; assert!(range.contains(23)); ```
There’s also the Within
trait, which does the same check, only with the range as the argument:
```rust use range_check::Within;
assert!(4123.iswithin(3000..5000)); assert!(23.iswithin(10..)); ```
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:
```rust use range_check::Check;
struct Clock { hour: i8, minute: i8, }
impl Clock {
fn new(hour: i8, minute: i8) -> rangecheck::Result
assert!(Clock::new(23, 59).isok()); assert!(Clock::new(24, 00).iserr()); ```
Displaying the Error
that gets returned in the error case shows you exactly which range failed to be satisfied:
```rust use std::string::ToString; use range_check::Check;
let failure = 13.checkrange(0..10).unwraperr(); asserteq!(failure.tostring(), "value (13) outside of range (0 .. 10)"); ```