turnip/lib.rs
1/// Recursive ternary operation for terse if-else statements.
2///
3/// # Uses
4///
5/// Provides brief if-else statement syntax similar to other languages.
6///
7/// Reducing the lines-of-code (LOC) of chained if-else conditional
8/// statements while improving the overall readability.
9///
10/// Other use-cases of `ifelse!` include providing natural recursion of chained
11/// conditional branches.
12///
13/// If only a value is entered, that value is returned. This is necessary to
14/// capture false statement remainders.
15///
16/// # Examples
17///
18/// ```
19/// use turnip::ifelse;
20///
21/// // A single if-else statement.
22/// ifelse!(1 < 0, true, false);
23///
24/// // Chained if-else statements.
25/// ifelse!(1 < 0, true, 1 > 0, true, false);
26/// ifelse!(1 < 0, true, 0 > 1, true, false);
27/// ifelse!(1 < 0, 0, 0 > 1, 1, 0 != 0, 2, 3);
28///
29/// // A single input returns itself.
30/// ifelse!(false);
31/// ```
32#[macro_export]
33macro_rules! ifelse {
34 ($cond:expr , $true_expr:expr , $($arg:tt)*) => {
35 if $cond {
36 $true_expr
37 } else {
38 ifelse!($($arg)*)
39 }
40 };
41 ($false_expr:expr) => ($false_expr);
42}
43
44#[cfg(test)]
45mod tests {
46
47 #[test]
48 fn ternary_macro() {
49 assert_eq!(ifelse!(1 < 0, true, false), false);
50 assert_eq!(ifelse!(1 < 0, true, 1 > 0, true, false), true);
51 assert_eq!(ifelse!(1 < 0, true, 1 < 0, true, false), false);
52 assert_eq!(ifelse!(false), false);
53 }
54}