1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4const OneBiggerInt = extras.OneBiggerInt;
5
6/// Allows u32 +% i16 to work
7pub 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
14test {
15 try std.testing.expect(safeAddWrap(@as(u16, 0), @as(i8, -2)) == 65534);
16}
17test {
18 try std.testing.expect(safeAddWrap(@as(u16, 10), @as(i8, -2)) == 8);
19}
20test {
21 try std.testing.expect(safeAddWrap(@as(u16, 65535), @as(i8, 1)) == 0);
22}
23test {
24 try std.testing.expect(safeAddWrap(@as(u16, 256), @as(i8, -128)) == 128);
25}