Commit aafbb9f
authored
Rollup merge of rust-lang#152179 - nickkuk:overflow-direction-note, r=jhpratt
Add documentation note about signed overflow direction
In rust-lang#151989 (comment) I noticed that signed overflow direction can be determined by returned wrapped value. It is not very obvious (especially, assuming additional `carry: bool` summand), but it is important if we want to add new leading (signed) limb to big integer in this case.
Examples for small summands `x, y: i8` with result extension:
| x | y | overflow | result as (u8, i8) |
| ---- | ---- | -------- | ------------------ |
| -1 | -128 | true | (127, -1) |
| 0 | -1 | false | (255, -1) |
| 2 | 2 | false | (4, 0) |
| 127 | 1 | true | (128, 0) |
Here is general proof.
1. Set $s=2^{N-1}$ and let's say `iN::carrying_add(x, y, c)` returns `(result, true)` then
$$
\mathrm{result}=\begin{cases}
x + y + c + 2s,& x + y + c \le -s-1,\\
x+y+c-2s,& x+y+c\ge s.
\end{cases}
$$
First case is overflowing below `iN::MIN` and we have
$$
\mathrm{result}\ge -s-s+0+2s =0;\qquad
\mathrm{result}=x + y + c + 2s\le -s-1+2s = s - 1,
$$
so we obtain $[0; s-1]$ which is exactly range of non-negative `iN`.
Second case is overflowing above `iN::MAX` and
$$
\mathrm{result}=x+y+c-2s\ge s-2s =-s;\qquad
\mathrm{result}\le s-1 + s-1+1-2s = -1,
$$
that is, $[-s,-1]$ which is exactly range of negative `iN`.
2. Now suppose that `iN::borrowing_sub(x,y,b)` returns `(result, true)` then
$$
\mathrm{result}=\begin{cases}
x - y - b + 2s,& x - y - b \le -s-1,\\
x - y - b - 2s,& x - y - b\ge s.
\end{cases}
$$
First case is overflowing below `iN::MIN` and we have
$$
\mathrm{result}\ge -s-(s-1)-1+2s =0;\qquad
\mathrm{result}=x - y - b + 2s\le -s-1+2s = s - 1.
$$
Second case is overflowing above `iN::MAX` and
$$
\mathrm{result}=x-y-b-2s\ge s-2s =-s;\qquad
\mathrm{result}\le s-1 - (-s) - 0 - 2s = -1.
$$1 file changed
Lines changed: 10 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2481 | 2481 | | |
2482 | 2482 | | |
2483 | 2483 | | |
2484 | | - | |
| 2484 | + | |
| 2485 | + | |
2485 | 2486 | | |
2486 | 2487 | | |
2487 | 2488 | | |
| |||
2516 | 2517 | | |
2517 | 2518 | | |
2518 | 2519 | | |
| 2520 | + | |
| 2521 | + | |
| 2522 | + | |
2519 | 2523 | | |
2520 | 2524 | | |
2521 | 2525 | | |
| |||
2583 | 2587 | | |
2584 | 2588 | | |
2585 | 2589 | | |
2586 | | - | |
| 2590 | + | |
| 2591 | + | |
2587 | 2592 | | |
2588 | 2593 | | |
2589 | 2594 | | |
| |||
2619 | 2624 | | |
2620 | 2625 | | |
2621 | 2626 | | |
| 2627 | + | |
| 2628 | + | |
| 2629 | + | |
2622 | 2630 | | |
2623 | 2631 | | |
2624 | 2632 | | |
| |||
0 commit comments