[−][src]Module type_freak::control
Compile-time guards and static assertions.
Overview
Most type operators in this module copies the input type to Self::Output
when certain conditions are met. We have these categories of operators:
- If<Output, Type>:
Asserts
Type
can be constructed. - IfPredicate<Output, Predicate>:
Asserts
Predicate
derives to True. - IfSame<Output, Lhs, Rhs>:
Asserts
Lhs
andRhs
are of the same type. - IfLess, IfLessOrEqual, IfGreater, IfGreaterOrEqual, IfEqual: Asserts two typenum numbers follows the order.
By convention, IfSameOutput<Output, Lhs, Rhs> is type alias of
<Output as IfSame<Lhs, Rhs>>::Output
trait cast, and others follow.
Only IfOutput<Output, Type> has no corresponding trait.
Static assertions
We can make use of If*Output
aliases to build compile time assertions.
For example, IfLessOutput asserts LHS
is less than RHS.
use typenum::consts::*; use type_freak::control::IfLessOutput; type Out1 = IfLessOutput<usize, U3, U5>; // U3 < U5 is true, thus Out1 ~= usize type Out2 = IfLessOutput<usize, U5, U3>; // U5 < U5 is false fn assert() { let _: Out1 = 0; // Goes fine here. let _: Out2 = 0; // Compile error!!! }
Compile-time guards
By placing If*
trait bounds in where
block. we can build compile-time
guarded functions. For example, we add IfSame
trait bound to assert two function
generic parameters have identical types.
The same trick applies to guarded structs, traits and impl blocks.
use type_freak::control::IfSame; fn guarded_function<Lhs, Rhs>() -> String where Lhs: IfSame<Lhs, Rhs> { "Yeeeeeee!".to_owned() } fn comile_me() { let _ = guarded_function::<String, String>(); // fine let _ = guarded_function::<String, u8>(); // Compile error!!! }
Traits
If | Returns input type if |
IfElseEqual | Returns output if left-hand-site equals to right-hand-side, otherwise returns |
IfElseGreater | Returns input type if |
IfElseGreaterOrEqual | Returns input type if |
IfElseLess | Returns input type if |
IfElseLessOrEqual | Returns input type if |
IfElsePredicate | Returns input type if |
IfEqual | Returns input type if |
IfGreater | Returns input type if |
IfGreaterOrEqual | Returns input type if |
IfLess | Returns input type if |
IfLessOrEqual | Returns input type if |
IfNonZero | A type operator that checks if a typenum value implements NonZero trait. |
IfNotPredicate | Returns input type if |
IfPredicate | Returns input type if |
IfSame | Returns input type if both |
IfZero | A type operator that checks if a typenum value is either B0, Z0 or U0. |