| ... | @@ -1062,10 +1062,11 @@ test "negateCast" { | ... | @@ -1062,10 +1062,11 @@ test "negateCast" { |
| 1062 | /// return null. | 1062 | /// return null. |
| 1063 | pub fn cast(comptime T: type, x: anytype) ?T { | 1063 | pub fn cast(comptime T: type, x: anytype) ?T { |
| 1064 | comptime assert(@typeInfo(T) == .Int); // must pass an integer | 1064 | comptime assert(@typeInfo(T) == .Int); // must pass an integer |
| 1065 | comptime assert(@typeInfo(@TypeOf(x)) == .Int); // must pass an integer | 1065 | const is_comptime = @TypeOf(x) == comptime_int; |
| 1066 | if (maxInt(@TypeOf(x)) > maxInt(T) and x > maxInt(T)) { | 1066 | comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .Int); // must pass an integer |
| | 1067 | if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) { |
| 1067 | return null; | 1068 | return null; |
| 1068 | } else if (minInt(@TypeOf(x)) < minInt(T) and x < minInt(T)) { | 1069 | } else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) { |
| 1069 | return null; | 1070 | return null; |
| 1070 | } else { | 1071 | } else { |
| 1071 | return @intCast(T, x); | 1072 | return @intCast(T, x); |
| ... | @@ -1073,12 +1074,18 @@ pub fn cast(comptime T: type, x: anytype) ?T { | ... | @@ -1073,12 +1074,18 @@ pub fn cast(comptime T: type, x: anytype) ?T { |
| 1073 | } | 1074 | } |
| 1074 | | 1075 | |
| 1075 | test "cast" { | 1076 | test "cast" { |
| | 1077 | try testing.expect(cast(u8, 300) == null); |
| 1076 | try testing.expect(cast(u8, @as(u32, 300)) == null); | 1078 | try testing.expect(cast(u8, @as(u32, 300)) == null); |
| | 1079 | try testing.expect(cast(i8, -200) == null); |
| 1077 | try testing.expect(cast(i8, @as(i32, -200)) == null); | 1080 | try testing.expect(cast(i8, @as(i32, -200)) == null); |
| | 1081 | try testing.expect(cast(u8, -1) == null); |
| 1078 | try testing.expect(cast(u8, @as(i8, -1)) == null); | 1082 | try testing.expect(cast(u8, @as(i8, -1)) == null); |
| | 1083 | try testing.expect(cast(u64, -1) == null); |
| 1079 | try testing.expect(cast(u64, @as(i8, -1)) == null); | 1084 | try testing.expect(cast(u64, @as(i8, -1)) == null); |
| 1080 | | 1085 | |
| | 1086 | try testing.expect(cast(u8, 255).? == @as(u8, 255)); |
| 1081 | try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255)); | 1087 | try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255)); |
| | 1088 | try testing.expect(@TypeOf(cast(u8, 255).?) == u8); |
| 1082 | try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8); | 1089 | try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8); |
| 1083 | } | 1090 | } |
| 1084 | | 1091 | |