aboutsummaryrefslogtreecommitdiff
path: root/lib/std/math.zig
diff options
context:
space:
mode:
authorVeikka Tuominen <git@vexu.eu>2022-12-18 01:57:49 +0200
committerGitHub <noreply@github.com>2022-12-18 01:57:49 +0200
commit901c3e96368bd9fa9ee9858c0295ee05ef1d7146 (patch)
treeb5a12345800be59ca68070ce1eff68479c98fff8 /lib/std/math.zig
parent9cc49548aa3f98b40a3d7a9cbc12d55ae7a9a298 (diff)
parent35750cd54f41477f25c77b8c44a220b57b40fd60 (diff)
downloadzig-901c3e96368bd9fa9ee9858c0295ee05ef1d7146.tar.gz
zig-901c3e96368bd9fa9ee9858c0295ee05ef1d7146.zip
Merge pull request #13552 from hryx/comparus-tautologicus
Sema: elide integer comparisons with guaranteed outcomes
Diffstat (limited to 'lib/std/math.zig')
-rw-r--r--lib/std/math.zig22
1 files changed, 22 insertions, 0 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig
index 58b6585884..c2e793ca8f 100644
--- a/lib/std/math.zig
+++ b/lib/std/math.zig
@@ -1437,6 +1437,19 @@ pub const CompareOperator = enum {
gt,
/// Not equal (`!=`)
neq,
+
+ /// Reverse the direction of the comparison.
+ /// Use when swapping the left and right hand operands.
+ pub fn reverse(op: CompareOperator) CompareOperator {
+ return switch (op) {
+ .lt => .gt,
+ .lte => .gte,
+ .gt => .lt,
+ .gte => .lte,
+ .eq => .eq,
+ .neq => .neq,
+ };
+ }
};
/// This function does the same thing as comparison operators, however the
@@ -1496,6 +1509,15 @@ test "order.compare" {
try testing.expect(order(1, 0).compare(.neq));
}
+test "compare.reverse" {
+ inline for (@typeInfo(CompareOperator).Enum.fields) |op_field| {
+ const op = @intToEnum(CompareOperator, op_field.value);
+ try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2));
+ try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3));
+ try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4));
+ }
+}
+
/// Returns a mask of all ones if value is true,
/// and a mask of all zeroes if value is false.
/// Compiles to one instruction for register sized integers.