[−][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:
- IfOutput<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
IfElsePredicate | A type operator that returns output depending Boolean condition. |
IfEqual | A type operator that checks if left-hand-site equals to right-hand-side. |
IfGreater | A type operator that checks if left-hand-site is greater than right-hand-side. |
IfGreaterOrEqual | A type operator that checks if left-hand-site is greater than or equals to right-hand-side. |
IfLess | A type operator that checks if left-hand-site is less than right-hand-side. |
IfLessOrEqual | A type operator that checks if left-hand-site is less than or equals to right-hand-side. |
IfNotPredicate | A type operator that checks if condition is False. |
IfPredicate | A type operator that checks if condition is True. |
IfSame | A type operator that checks you both types are equivalent. |
Type Definitions
IfElsePredicateOutput | |
IfEqualOutput | |
IfGreaterOrEqualOutput | |
IfGreaterOutput | |
IfLessOrEqualOutput | |
IfLessOutput | |
IfNotPredicateOutput | |
IfOutput | A type alias that checks if type can be constructed. |
IfPredicateOutput | |
IfSameOutput |