1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
#[macro_export]
/// ## Ternary Operator
///
/// condition ? true : false
///
/// ## Examples
/// ```rust
/// use op::ternary;
///
/// let n = ternary!(true => 0, 1);
/// assert_eq!(n, 0);
/// let n = ternary!(false => 0, 1);
/// assert_eq!(n, 1);
/// ````
macro_rules! ternary {
($condition:expr => $true:expr; $false:expr) => {
if $condition {
$true
} else {
$false
}
};
($condition:expr => $true:expr, $false:expr) => {
if $condition {
$true
} else {
$false
}
};
}
#[macro_export]
/// A simple macro that handle `Option<T>`.
macro_rules! some {
($arg:expr; $err:expr) => {
if let Some(v) = $arg {
v
} else {
$err
}
};
($arg:expr; ret) => {
if let Some(v) = $arg {
v
} else {
return;
}
};
($arg:expr; ret $result:expr) => {
if let Some(v) = $arg {
v
} else {
return $result;
}
};
($arg:expr; con) => {
if let Some(v) = $arg {
v
} else {
continue;
}
};
}
#[macro_export]
/// A simple macro that handle `Result<T, E>`.
macro_rules! result {
($arg:expr; $err:expr) => {
if let Ok(v) = $arg {
v
} else {
$err
}
};
($arg:expr; ret) => {
if let Ok(v) = $arg {
v
} else {
return;
}
};
($arg:expr; ret $result:expr) => {
if let Ok(v) = $arg {
v
} else {
return $result;
}
};
($arg:expr; con) => {
if let Ok(v) = $arg {
v
} else {
continue;
}
};
}
/// A simple macro that catch `Result<T, E>` and `Option<T>`
///
/// # Examples
/// ```
/// use op::catch;
///
/// let result1: Result<i32, i32> = Ok(1);
/// let result2: Result<i32, i32> = Ok(2);
/// assert_eq!(Ok(3), catch!(i32 -> Ok(result1? + result2?)));
///
/// let option1: Option<i32> = Some(1);
/// let option2: Option<i32> = Some(2);
/// assert_eq!(Some(3), catch!(Some(option1? + option2?)));
/// ```
#[macro_export]
macro_rules! catch {
($e:ident -> $stmt:stmt) => {{
let catch = || -> std::result::Result<_, $e> { $stmt };
catch()
}};
($stmt:stmt) => {{
let catch = || -> std::option::Option<_> { $stmt };
catch()
}};
}