Crate range_check [] [src]

This is a little library that helps with range and bounds checking. It works with Rust’s standard Range, RangeFrom, and RangeTo types.

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 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:

use range_check::Within;

assert!(4123.is_within(3000..5000));
assert!(23.is_within(10..));

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 Results that contain debugging information for when a value doesn’t lie within a range:

use range_check::Check;

struct Clock {
    hour: i8,
    minute: i8,
}

impl Clock {
    fn new(hour: i8, minute: i8) -> range_check::Result<Clock, i8> {
        Ok(Clock {
            hour:   try!(hour.check_range(0..24)),
            minute: try!(minute.check_range(0..60)),
        })
    }
}

assert!(Clock::new(23, 59).is_ok());
assert!(Clock::new(24, 00).is_err());

Displaying the Error that gets returned in the error case shows you exactly which range failed to be satisfied:

use std::string::ToString;
use range_check::Check;

let failure = 13.check_range(0..10).unwrap_err();
assert_eq!(failure.to_string(), "value (13) outside of range (0 .. 10)");

Structs

Bounds

The two bounds destructured from a Range value.

Error

The error that gets thrown when a check_range fails.

Traits

Bounded

Trait to get the bounds of ranges.

Check

Trait that provides early returns for failed range checks using Results.

Contains

A trait for all range-type values.

Within

A trait for values that could be contained in a range.

Type Definitions

Result

Type alias for a Result with an Error wrapping the result’s error type.