Expand description

option-operations provides traits and auto-implementations to improve arithmetic operations usability when dealing with Options.

Example

Dealing with two Options, can lead to verbose expressions:

let lhs = Some(1u64);
let rhs = Some(u64::MAX);

assert_eq!(
    lhs.zip(rhs).map(|(lhs, rhs)| lhs.saturating_add(rhs)),
    Some(u64::MAX),
);

Thanks to the trait OptionSaturatingAdd we can write:

assert_eq!(
    lhs.opt_saturating_add(rhs),
    Some(u64::MAX),
);

The trait can also be used with the inner type:

assert_eq!(
    lhs.opt_saturating_add(u64::MAX),
    Some(u64::MAX),
);

assert_eq!(
    1.opt_saturating_add(rhs),
    Some(u64::MAX),
);

Alternative to PartialOrd for Option<T>

Another purpose is to workaround the PartiaOrd implementation for Option<T>, which uses the declaration order of the variants for Option. None appearing before Some(_), it results in the following behavior:

let some_0 = Some(0);
let none: Option<u64> = None;

assert_eq!(none.partial_cmp(&some_0), Some(Ordering::Less));
assert_eq!(some_0.partial_cmp(&none), Some(Ordering::Greater));

In some cases, we might consider that None reflects a value which is not defined and thus can not be compared with Some(_).

assert_eq!(none.opt_cmp(&some_0), None);
assert_eq!(some_0.opt_cmp(&none), None);

Of course, this is consistent with other usual comparisons:

assert_eq!(none.opt_lt(&some_0), None);
assert_eq!(none.opt_min(some_0), None);

Re-exports

pub use add::OptionAdd;
pub use add::OptionAddAssign;
pub use add::OptionCheckedAdd;
pub use add::OptionOverflowingAdd;
pub use add::OptionSaturatingAdd;
pub use add::OptionWrappingAdd;
pub use error::Error;
pub use div::OptionCheckedDiv;
pub use div::OptionDiv;
pub use div::OptionDivAssign;
pub use div::OptionOverflowingDiv;
pub use div::OptionWrappingDiv;
pub use eq::OptionEq;
pub use min_max::OptionMinMax;
pub use mul::OptionCheckedMul;
pub use mul::OptionMul;
pub use mul::OptionMulAssign;
pub use mul::OptionOverflowingMul;
pub use mul::OptionSaturatingMul;
pub use mul::OptionWrappingMul;
pub use ord::OptionOrd;
pub use rem::OptionCheckedRem;
pub use rem::OptionOverflowingRem;
pub use rem::OptionRem;
pub use rem::OptionRemAssign;
pub use rem::OptionWrappingRem;
pub use sub::OptionCheckedSub;
pub use sub::OptionOverflowingSub;
pub use sub::OptionSaturatingSub;
pub use sub::OptionSub;
pub use sub::OptionSubAssign;
pub use sub::OptionWrappingSub;

Modules

Traits for the addition OptionOperations.

Traits for the division OptionOperations.

Trait for the equality OptionOperations.

Error type which can be returned by some OptionOperations.

Traits for the minimun and maximum OptionOperations.

Traits for the multiplication OptionOperations.

Trait for the order OptionOperations.

Traits for the remainder OptionOperations.

Traits for the substraction OptionOperations.

Traits

Trait for inner types participating in option-operations.