Cast an integer to a different integer type. If the value doesn't fit, return null.
pub fn cast(comptime T: type, x: anytype) ?T
pub fn cast(comptime T: type, x: anytype) ?T {
comptime assert(@typeInfo(T) == .int); // must pass an integer
const is_comptime = @TypeOf(x) == comptime_int;
comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .int); // must pass an integer
if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) {
return null;
} else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) {
return null;
} else {
return @as(T, @intCast(x));
}
}