castingundefined-behaviorzig

How to safely cast integer in zig


The @intCast() causes undefined behavior when the target type cannot hold the resulting value. Is there something like @safeIntCast() or a similar function which would return CastError!anytype?


Solution

  • std.math has a number of functions for safe casting:

    Cast an integer to a different integer type. If the value doesn't fit, return null.

    Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by, the new type, it will be converted to the closest possible representation.

    Returns the negation of the integer parameter. Result is a signed integer.