authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-10 19:04:22-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-10 19:04:22-07:00
log1295525a7afe76d0ac384b3f74927ac22b27ec09
tree3609306627c17f83745046cccbde57760088eb4d
parente1d8073d2fc0df6fbc5ce983312e3da374a9889b
parent169810b20fb6ce036ed0ff2990f06751aa11e623

Merge branch 'AdamGoertz-master'

closes #5080 closes #6887

1 files changed, 42 insertions(+), 6 deletions(-)

lib/std/math.zig+42-6
......@@ -1070,16 +1070,52 @@ test "std.math.log2_int_ceil" {
10701070 testing.expect(log2_int_ceil(u32, 10) == 4);
10711071}
10721072
1073///Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by,
1074///the new type, it will be converted to the closest possible representation.
10731075pub fn lossyCast(comptime T: type, value: anytype) T {
1074 switch (@typeInfo(@TypeOf(value))) {
1075 .Int => return @intToFloat(T, value),
1076 .Float => return @floatCast(T, value),
1077 .ComptimeInt => return @as(T, value),
1078 .ComptimeFloat => return @as(T, value),
1079 else => @compileError("bad type"),
1076 switch (@typeInfo(T)) {
1077 .Float => {
1078 switch (@typeInfo(@TypeOf(value))) {
1079 .Int => return @intToFloat(T, value),
1080 .Float => return @floatCast(T, value),
1081 .ComptimeInt => return @as(T, value),
1082 .ComptimeFloat => return @as(T, value),
1083 else => @compileError("bad type"),
1084 }
1085 },
1086 .Int => {
1087 switch (@typeInfo(@TypeOf(value))) {
1088 .Int, .ComptimeInt => {
1089 if (value > maxInt(T)) {
1090 return @as(T, maxInt(T));
1091 } else if (value < minInt(T)) {
1092 return @as(T, minInt(T));
1093 } else {
1094 return @intCast(T, value);
1095 }
1096 },
1097 .Float, .ComptimeFloat => {
1098 if (value > maxInt(T)) {
1099 return @as(T, maxInt(T));
1100 } else if (value < minInt(T)) {
1101 return @as(T, minInt(T));
1102 } else {
1103 return @floatToInt(T, value);
1104 }
1105 },
1106 else => @compileError("bad type"),
1107 }
1108 },
1109 else => @compileError("bad result type"),
10801110 }
10811111}
10821112
1113test "math.lossyCast" {
1114 testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
1115 testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
1116 testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
1117}
1118
10831119test "math.f64_min" {
10841120 const f64_min_u64 = 0x0010000000000000;
10851121 const fmin: f64 = f64_min;