| 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 safeAddWrap(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(safeAddWrap(@as(u16, 0), @as(i8, -2)) == 65534); |
| 16 | } |
| 17 | test { |
| 18 | try std.testing.expect(safeAddWrap(@as(u16, 10), @as(i8, -2)) == 8); |
| 19 | } |
| 20 | test { |
| 21 | try std.testing.expect(safeAddWrap(@as(u16, 65535), @as(i8, 1)) == 0); |
| 22 | } |
| 23 | test { |
| 24 | try std.testing.expect(safeAddWrap(@as(u16, 256), @as(i8, -128)) == 128); |
| 25 | } |