Skip to content

Add documentation note about signed overflow direction#152179

Open
nickkuk wants to merge 1 commit intorust-lang:mainfrom
nickkuk:overflow-direction-note
Open

Add documentation note about signed overflow direction#152179
nickkuk wants to merge 1 commit intorust-lang:mainfrom
nickkuk:overflow-direction-note

Conversation

@nickkuk
Copy link
Contributor

@nickkuk nickkuk commented Feb 5, 2026

In #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.

  1. 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. $$

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Feb 5, 2026
@rustbot
Copy link
Collaborator

rustbot commented Feb 5, 2026

r? @scottmcm

rustbot has assigned @scottmcm.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants