| ... | ... | @@ -1070,16 +1070,44 @@ test "std.math.log2_int_ceil" { |
| 1070 | 1070 | testing.expect(log2_int_ceil(u32, 10) == 4); |
| 1071 | 1071 | } |
| 1072 | 1072 | |
| 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. |
| 1073 | 1075 | pub 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)) { return @as(T, maxInt(T)); } |
| 1090 | else if (value < minInt(T)) { return @as(T, minInt(T)); } |
| 1091 | else { return @intCast(T, value); } |
| 1092 | }, |
| 1093 | .Float, .ComptimeFloat => { |
| 1094 | if (value > maxInt(T)) { return @as(T, maxInt(T)); } |
| 1095 | else if (value < minInt(T)) { return @as(T, minInt(T)); } |
| 1096 | else { return @floatToInt(T, value); } |
| 1097 | }, |
| 1098 | else => @compileError("bad type"), |
| 1099 | } |
| 1100 | }, |
| 1101 | else => @compileError("bad result type"), |
| 1080 | 1102 | } |
| 1081 | 1103 | } |
| 1082 | 1104 | |
| 1105 | test "math.lossyCast" { |
| 1106 | testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767)); |
| 1107 | testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0)); |
| 1108 | testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200)); |
| 1109 | } |
| 1110 | |
| 1083 | 1111 | test "math.f64_min" { |
| 1084 | 1112 | const f64_min_u64 = 0x0010000000000000; |
| 1085 | 1113 | const fmin: f64 = f64_min; |