From 4512f277849a7e1a0e221c051d654c58ecf771ae Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 7 May 2025 17:07:26 -0700 Subject: [PATCH] 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. --- lib/std/math.zig | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/std/math.zig b/lib/std/math.zig index 1cd9a83a14..61eeba44c5 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -570,6 +570,15 @@ pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) { return ov[0]; } +/// Returns the sum of `a` and `b`, which can be any integer types, including +/// different ones from each other, or else returns `null` indicating the +/// result cannot fit inside the provided `Result` type. +pub fn addAny(comptime Result: type, a: anytype, b: anytype) ?Result { + if (Result == comptime_int) return @as(comptime_int, a) + @as(comptime_int, b); + const O = std.meta.Int(.signed, @max(@bitSizeOf(@TypeOf(a)), @bitSizeOf(@TypeOf(b))) + 1); + return cast(Result, @as(O, a) + @as(O, b)); +} + /// Returns a - b, or an error on overflow. pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) { if (T == comptime_int) return a - b;