authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-05-07 17:07:26-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-01 16:35:29-07:00
log4512f277849a7e1a0e221c051d654c58ecf771ae
tree1f6779e12f4b9d03c3a297bbf5c4469a7de1e804
parent803215bb186cb4a16f2f9552749a18fa384634e6

introduce std.math.addAny

I think this is generally more useful than the existing add function because it doesn't unnecessarily rely on the types of the operands - the error only occurs if the final mathematical result cannot be stored in the desired result type.

1 files changed, 9 insertions(+), 0 deletions(-)

lib/std/math.zig+9
......@@ -570,6 +570,15 @@ pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) {
570570 return ov[0];
571571}
572572
573/// Returns the sum of `a` and `b`, which can be any integer types, including
574/// different ones from each other, or else returns `null` indicating the
575/// result cannot fit inside the provided `Result` type.
576pub fn addAny(comptime Result: type, a: anytype, b: anytype) ?Result {
577 if (Result == comptime_int) return @as(comptime_int, a) + @as(comptime_int, b);
578 const O = std.meta.Int(.signed, @max(@bitSizeOf(@TypeOf(a)), @bitSizeOf(@TypeOf(b))) + 1);
579 return cast(Result, @as(O, a) + @as(O, b));
580}
581
573582/// Returns a - b, or an error on overflow.
574583pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) {
575584 if (T == comptime_int) return a - b;