- match u64::checked_add(a, b) {
- Some(sum) if !carry => (sum, false),
- Some(sum) => { // we have to increment the sum by 1, where it may overflow again
- match u64::checked_add(sum, 1) {
- Some(total_sum) => (total_sum, false),
- None => (0, true) // we overflowed incrementing by 1, so we are just "at the edge"
- }
- },
- None => {
- // Get the remainder, i.e., the wrapping sum. This cannot overflow again by adding just 1, so it is safe
- // to add the carry here.
- let rem = u64::wrapping_add(a, b) + if carry { 1 } else { 0 };
- (rem, true)
- }
+ let sum = u64::wrapping_add(a, b);
+ let carry_n = if carry { 1 } else { 0 };
+ if sum >= a { // the first sum did not overflow
+ let sum_total = u64::wrapping_add(sum, carry_n);
+ let had_overflow = sum_total < sum;
+ (sum_total, had_overflow)
+ } else { // the first sum did overflow
+ // it is impossible for this to overflow again, as we are just adding 0 or 1
+ (sum + carry_n, true)