macrors/
operator.rs

1/*
2 * Copyright © 2024 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// ----------------------------------------------------------------
18
19/// A macro for ternary conditional operation([wiki](https://en.wikipedia.org/wiki/Ternary_conditional_operator)) in rust.
20///
21/// This macro evaluates a condition and returns one of two expressions based on whether the condition
22/// is true or false.
23///
24/// # Examples:
25///
26///```rust
27/// use macrors::ternary;
28///
29/// let x = 5;
30/// let y = 10;
31///
32/// let result = ternary!(x < y, "x is less than y", "x is not less than y");
33/// assert_eq!(result, "x is less than y");
34/// ```
35/// ```
36#[macro_export]
37macro_rules! ternary {
38    ($condition:expr, $value_true:expr, $value_false:expr) => {
39        if $condition {
40            $value_true
41        } else {
42            $value_false
43        }
44    };
45}
46
47/// A macro for ternary conditional operation with equality comparison.
48///
49/// This macro compares two values and returns one of two expressions based on whether the values
50/// are equal or not.
51///
52/// # Examples
53///
54/// ```rust
55/// use macrors::ternary_eq;
56///
57/// let x = 5;
58/// let y = 10;
59///
60/// let result_eq = ternary_eq!(x, y, "x is equal to y", "x is not equal to y");
61/// assert_eq!(result_eq, "x is not equal to y");
62/// ```
63#[macro_export]
64macro_rules! ternary_eq {
65    ($left:expr, $right:expr, $true_expr:expr, $false_expr:expr) => {
66        if $left == $right {
67            $true_expr
68        } else {
69            $false_expr
70        }
71    };
72}
73
74/// A macro for ternary conditional operation with equality comparison.
75///
76/// This macro compares two values and returns one of two expressions based on whether the values
77/// are equal or not.
78///
79/// # Examples
80///
81/// ```
82/// use macrors::ternary_eq;
83///
84/// let x = 5;
85/// let y = 10;
86///
87/// let result_eq = ternary_eq!(x, y, "x is equal to y", "x is not equal to y");
88/// assert_eq!(result_eq, "x is not equal to y");
89/// ```
90#[macro_export]
91macro_rules! ternary_ne {
92    ($left:expr, $right:expr, $true_expr:expr, $false_expr:expr) => {
93        if $left != $right {
94            $true_expr
95        } else {
96            $false_expr
97        }
98    };
99}