authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-10 19:04:10-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-10 19:04:10-07:00
log169810b20fb6ce036ed0ff2990f06751aa11e623
tree3609306627c17f83745046cccbde57760088eb4d
parent0f32de77c91a3761a4434d1790018b5c2c6fa099

zig fmt


1 files changed, 16 insertions(+), 8 deletions(-)

lib/std/math.zig+16-8
...@@ -1073,7 +1073,7 @@ test "std.math.log2_int_ceil" {...@@ -1073,7 +1073,7 @@ test "std.math.log2_int_ceil" {
1073///Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by,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.1074///the new type, it will be converted to the closest possible representation.
1075pub fn lossyCast(comptime T: type, value: anytype) T {1075pub fn lossyCast(comptime T: type, value: anytype) T {
1076 switch(@typeInfo(T)) {1076 switch (@typeInfo(T)) {
1077 .Float => {1077 .Float => {
1078 switch (@typeInfo(@TypeOf(value))) {1078 switch (@typeInfo(@TypeOf(value))) {
1079 .Int => return @intToFloat(T, value),1079 .Int => return @intToFloat(T, value),
...@@ -1084,16 +1084,24 @@ pub fn lossyCast(comptime T: type, value: anytype) T {...@@ -1084,16 +1084,24 @@ pub fn lossyCast(comptime T: type, value: anytype) T {
1084 }1084 }
1085 },1085 },
1086 .Int => {1086 .Int => {
1087 switch(@typeInfo(@TypeOf(value))) {1087 switch (@typeInfo(@TypeOf(value))) {
1088 .Int, .ComptimeInt => {1088 .Int, .ComptimeInt => {
1089 if (value > maxInt(T)) { return @as(T, maxInt(T)); }1089 if (value > maxInt(T)) {
1090 else if (value < minInt(T)) { return @as(T, minInt(T)); }1090 return @as(T, maxInt(T));
1091 else { return @intCast(T, value); }1091 } else if (value < minInt(T)) {
1092 return @as(T, minInt(T));
1093 } else {
1094 return @intCast(T, value);
1095 }
1092 },1096 },
1093 .Float, .ComptimeFloat => {1097 .Float, .ComptimeFloat => {
1094 if (value > maxInt(T)) { return @as(T, maxInt(T)); }1098 if (value > maxInt(T)) {
1095 else if (value < minInt(T)) { return @as(T, minInt(T)); }1099 return @as(T, maxInt(T));
1096 else { return @floatToInt(T, value); }1100 } else if (value < minInt(T)) {
1101 return @as(T, minInt(T));
1102 } else {
1103 return @floatToInt(T, value);
1104 }
1097 },1105 },
1098 else => @compileError("bad type"),1106 else => @compileError("bad type"),
1099 }1107 }