| 1 | const std = @import("std"); |
| 2 | const string = []const u8; |
| 3 | const extras = @import("./lib.zig"); |
| 4 | const OneBiggerInt = extras.OneBiggerInt; |
| 5 | |
| 6 | /// Allows u32 + i16 to work |
| 7 | pub fn safeAdd(a: anytype, b: anytype) @TypeOf(a) { |
| 8 | if (b >= 0) { |
| 9 | return a + @as(@TypeOf(a), @intCast(b)); |
| 10 | } |
| 11 | return a - @as(@TypeOf(a), @intCast(-@as(OneBiggerInt(@TypeOf(b)), b))); |
| 12 | } |
| 13 | |
| 14 | test { |
| 15 | try std.testing.expect(safeAdd(@as(u16, 10), @as(i8, -2)) == 8); |
| 16 | } |
| 17 | test { |
| 18 | try std.testing.expect(safeAdd(@as(u16, 256), @as(i8, -128)) == 128); |
| 19 | } |