From 69b784ff52248663df210e9899bdbf9a4923a40e Mon Sep 17 00:00:00 2001 From: Stevie Hryciw Date: Mon, 14 Nov 2022 15:51:44 -0800 Subject: [PATCH] std: add CompareOperator.reverse --- lib/std/math.zig | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) 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.