Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created April 2, 2022 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/73f5a11e680cd90b0ac000e20ee0a98f to your computer and use it in GitHub Desktop.
Save hnakamur/73f5a11e680cd90b0ac000e20ee0a98f to your computer and use it in GitHub Desktop.
modified std.math.cast to support .ComptimeInt as well as .Int
const std = @import("std");
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
const minInt = std.math.minInt;
pub fn cast(comptime T: type, x: anytype) (error{Overflow}!T) {
comptime assert(@typeInfo(T) == .Int); // must pass an integer
comptime assert(@typeInfo(@TypeOf(x)) == .Int or
@typeInfo(@TypeOf(x)) == .ComptimeInt); // must pass an integer or comptimeint
if (x > maxInt(T)) {
return error.Overflow;
} else if (x < minInt(T)) {
return error.Overflow;
} else {
return @intCast(T, x);
}
}
const testing = std.testing;
test "cast" {
{ // .Int
try testing.expectEqual(@as(i8, -128), try cast(i8, @as(i32, -128)));
try testing.expectError(error.Overflow, cast(i8, @as(i32, -129)));
try testing.expectError(error.Overflow, cast(u8, @as(u32, 300)));
try testing.expectError(error.Overflow, cast(i8, @as(i32, -200)));
try testing.expectError(error.Overflow, cast(u8, @as(i8, -1)));
try testing.expectError(error.Overflow, cast(u64, @as(i8, -1)));
try testing.expect((try cast(u8, @as(u32, 255))) == @as(u8, 255));
try testing.expect(@TypeOf(try cast(u8, @as(u32, 255))) == u8);
}
{ // .ComptimeInt
try testing.expectEqual(@as(i8, -128), try cast(i8, -128));
try testing.expectError(error.Overflow, cast(i8, -129));
try testing.expectError(error.Overflow, cast(u8, 300));
try testing.expectError(error.Overflow, cast(i8, -200));
try testing.expectError(error.Overflow, cast(u8, -1));
try testing.expectError(error.Overflow, cast(u64, -1));
try testing.expect((try cast(u8, 255)) == @as(u8, 255));
try testing.expect(@TypeOf(try cast(u8, 255)) == u8);
}
}
@hnakamur
Copy link
Author

hnakamur commented Apr 2, 2022

maxInt(@TypeOf(x)) > maxInt(T) and minInt(@TypeOf(x)) < minInt(T) in the current std.math.cast
https://github.com/ziglang/zig/blob/3ee44ce949117e8e91348ef870b18b23571a408d/lib/std/math.zig#L1008-L1018
were added in the commit ziglang/zig@5b00dee
in order to handle signed integers.

It seems unnecessary since tests in the modified version of std.math.cast passes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment