aboutsummaryrefslogtreecommitdiff
path: root/lib/std
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2019-12-16 11:39:13 -0500
committerAndrew Kelley <andrew@ziglang.org>2019-12-16 11:39:13 -0500
commit496f271d179fac0ce05dc68eb3fddad12384fd68 (patch)
tree615f80e03f2bfdf021cc387956b0f38e2a5ba32f /lib/std
parentfe0e8c87b762aba6eb5ff1fad8ad7d37404476f1 (diff)
parent1cad0acc7e4450d2f114ea87da2fd88b81694332 (diff)
downloadzig-496f271d179fac0ce05dc68eb3fddad12384fd68.tar.gz
zig-496f271d179fac0ce05dc68eb3fddad12384fd68.zip
Merge branch 'shawnl-lessThan'
* always allow integer comparison operations no matter the bit width, signedness, or comptime-ness of operands. closes #2133 * implement comparisons for vectors, which returns vector of bools. closes #3001
Diffstat (limited to 'lib/std')
-rw-r--r--lib/std/math.zig55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig
index b3b50beac6..a12bf5f4e9 100644
--- a/lib/std/math.zig
+++ b/lib/std/math.zig
@@ -943,3 +943,58 @@ test "math.mulWide" {
testing.expect(mulWide(i8, 5, -5) == -25);
testing.expect(mulWide(u8, 100, 100) == 10000);
}
+
+/// Not to be confused with `std.mem.Compare`.
+pub const CompareOperator = enum {
+ /// Less than (`<`)
+ lt,
+
+ /// Less than or equal (`<=`)
+ lte,
+
+ /// Equal (`==`)
+ eq,
+
+ /// Greater than or equal (`>=`)
+ gte,
+
+ /// Greater than (`>`)
+ gt,
+
+ /// Not equal (`!=`)
+ neq,
+};
+
+/// This function does the same thing as comparison operators, however the
+/// operator is a runtime-known enum value. Works on any operands that
+/// support comparison operators.
+pub fn compare(a: var, op: CompareOperator, b: var) bool {
+ return switch (op) {
+ .lt => a < b,
+ .lte => a <= b,
+ .eq => a == b,
+ .neq => a != b,
+ .gt => a > b,
+ .gte => a >= b,
+ };
+}
+
+test "math.lt, et al < <= > >= between signed and unsigned" {
+ testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255)));
+ testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1)));
+ testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255)));
+ testing.expect(compare(@as(u8, 255), .gt, @as(i8, -1)));
+ testing.expect(!compare(@as(u8, 255), .lte, @as(i8, -1)));
+ testing.expect(compare(@as(i8, -1), .lt, @as(u9, 255)));
+ testing.expect(!compare(@as(i8, -1), .gte, @as(u9, 255)));
+ testing.expect(compare(@as(u9, 255), .gt, @as(i8, -1)));
+ testing.expect(!compare(@as(u9, 255), .lte, @as(i8, -1)));
+ testing.expect(compare(@as(i9, -1), .lt, @as(u8, 255)));
+ testing.expect(!compare(@as(i9, -1), .gte, @as(u8, 255)));
+ testing.expect(compare(@as(u8, 255), .gt, @as(i9, -1)));
+ testing.expect(!compare(@as(u8, 255), .lte, @as(i9, -1)));
+ testing.expect(compare(@as(u8, 1), .lt, @as(u8, 2)));
+ testing.expect(@bitCast(u8, @as(i8, -1)) == @as(u8, 255));
+ testing.expect(!compare(@as(u8, 255), .eq, @as(i8, -1)));
+ testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1)));
+}