| ... | @@ -1070,16 +1070,52 @@ test "std.math.log2_int_ceil" { | ... | @@ -1070,16 +1070,52 @@ test "std.math.log2_int_ceil" { |
| 1070 | testing.expect(log2_int_ceil(u32, 10) == 4); | 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 | pub fn lossyCast(comptime T: type, value: anytype) T { | 1075 | pub fn lossyCast(comptime T: type, value: anytype) T { |
| 1074 | switch (@typeInfo(@TypeOf(value))) { | 1076 | switch (@typeInfo(T)) { |
| 1075 | .Int => return @intToFloat(T, value), | 1077 | .Float => { |
| 1076 | .Float => return @floatCast(T, value), | 1078 | switch (@typeInfo(@TypeOf(value))) { |
| 1077 | .ComptimeInt => return @as(T, value), | 1079 | .Int => return @intToFloat(T, value), |
| 1078 | .ComptimeFloat => return @as(T, value), | 1080 | .Float => return @floatCast(T, value), |
| 1079 | else => @compileError("bad type"), | 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"), |
| 1080 | } | 1110 | } |
| 1081 | } | 1111 | } |
| 1082 | | 1112 | |
| | 1113 | test "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 | |
| 1083 | test "math.f64_min" { | 1119 | test "math.f64_min" { |
| 1084 | const f64_min_u64 = 0x0010000000000000; | 1120 | const f64_min_u64 = 0x0010000000000000; |
| 1085 | const fmin: f64 = f64_min; | 1121 | const fmin: f64 = f64_min; |