Commit 078a0a6999

Wink Saville <wink@saville.com>
2018-11-25 19:10:44
Add math min/max for Float and Value
1 parent c54fe0d
Changed files (1)
std
std/math/index.zig
@@ -777,3 +777,92 @@ test "max value type" {
     const x: u32 = maxInt(i32);
     assert(x == 2147483647);
 }
+
+pub fn maxFloat(comptime T: type) T {
+    return switch (T) {
+        f16 => f16_max,
+        f32 => f32_max,
+        f64 => f64_max,
+        else => @compileError("Expecting type to be a float"),
+    };
+}
+
+test "math.maxFloat" {
+    assert(maxFloat(f16) == f16_max);
+    assert(maxFloat(f32) == f32_max);
+    assert(maxFloat(f64) == f64_max);
+}
+
+pub fn minFloat(comptime T: type) T {
+    return switch (T) {
+        f16 => f16_min,
+        f32 => f32_min,
+        f64 => f64_min,
+        else => @compileError("Expecting type to be a float"),
+    };
+}
+
+test "math.minFloat" {
+    assert(minFloat(f16) == f16_min);
+    assert(minFloat(f32) == f32_min);
+    assert(minFloat(f64) == f64_min);
+}
+
+pub fn maxValue(comptime T: type) T {
+    return switch (@typeId(T)) {
+        TypeId.Int => maxInt(T),
+        TypeId.Float => maxFloat(T),
+        else => @compileError("Expecting type to be a float or int"),
+    };
+}
+
+test "math.maxValue" {
+    assert(maxValue(u0) == 0);
+    assert(maxValue(u1) == 1);
+    assert(maxValue(u8) == 255);
+    assert(maxValue(u16) == 65535);
+    assert(maxValue(u32) == 4294967295);
+    assert(maxValue(u64) == 18446744073709551615);
+
+    assert(maxValue(i0) == 0);
+    assert(maxValue(i1) == 0);
+    assert(maxValue(i8) == 127);
+    assert(maxValue(i16) == 32767);
+    assert(maxValue(i32) == 2147483647);
+    assert(maxValue(i63) == 4611686018427387903);
+    assert(maxValue(i64) == 9223372036854775807);
+
+    assert(maxValue(f16) == f16_max);
+    assert(maxValue(f32) == f32_max);
+    assert(maxValue(f64) == f64_max);
+}
+
+pub fn minValue(comptime T: type) T {
+    return switch (@typeId(T)) {
+        TypeId.Int => minInt(T),
+        TypeId.Float => minFloat(T),
+        else => @compileError("Expecting type to be a float or int"),
+    };
+}
+
+test "math.minValue" {
+    assert(minValue(u0) == 0);
+    assert(minValue(u1) == 0);
+    assert(minValue(u8) == 0);
+    assert(minValue(u16) == 0);
+    assert(minValue(u32) == 0);
+    assert(minValue(u63) == 0);
+    assert(minValue(u64) == 0);
+
+    assert(minValue(i0) == 0);
+    assert(minValue(i1) == -1);
+    assert(minValue(i8) == -128);
+    assert(minValue(i16) == -32768);
+    assert(minValue(i32) == -2147483648);
+    assert(minValue(i63) == -4611686018427387904);
+    assert(minValue(i64) == -9223372036854775808);
+
+    assert(minValue(f16) == f16_min);
+    assert(minValue(f32) == f32_min);
+    assert(minValue(f64) == f64_min);
+}