The arithmetic swap in my crate overflows on i32::MAX and returns the right answer anyway. The three wraps cancel out.

The debug build of the same call dies on the first line.

The crate ships the XOR swap. The same file also contains an arithmetic swap and a one-line tuple swap, and it calls neither of them.

All three are in src/main.rs:

impl Solution {
    pub fn swap(a: i32, b: i32) -> (i32, i32) {
        // Self::inplace_math(a, b)
        Self::xor_swap(a, b)
    }

    fn implicit_swap(a: i32, b: i32) -> (i32, i32) {
        (b, a)
    }

    fn inplace_math(a: i32, b: i32) -> (i32, i32) {
        let a = a + b;
        let b = a - b;
        let a = (a - b);
        (a, b)
    }

    fn xor_swap(a: i32, b: i32) -> (i32, i32) {
        let a = a ^ b;
        let b = a ^ b;
        let a = a ^ b;
        (a, b)
    }
}

The order the three functions appear in the file is tuple, arithmetic, XOR, and the commented-out line at the call site is the record of the arithmetic version being tried before the XOR one. The tuple version has no commented-out call site at all. It is the simplest of the three, and it is the one the problem statement’s first hint points at.

Where the overflow happens

inplace_math computes a + b and stores it back in a. With a = i32::MAX and b = 1, that is 2147483648, which does not fit in an i32.

In a debug build:

attempt to add with overflow

In a release build the same expression wraps, and the function goes on to return (1, 2147483647), which happens to be the correct answer. The wrap cancels out across the three lines. That is a coincidence, not a property. The arithmetic swap is only correct as long as the intermediate a + b is representable, or as long as the wraps happen to compose back into the right answer.

I want to be precise about the input, because it matters. The problem’s constraint is -10^9 <= a, b <= 10^9, and i32::MAX is 2147483647, so that input is outside the stated range. Inside the range, the arithmetic version does not overflow: the worst case is 10^9 + 10^9 = 2000000000, which still fits inside i32::MAX at 2147483647. The constraint is the only thing keeping it safe, and it holds with about 147 million to spare.

That is a real difference from the other two versions. implicit_swap and xor_swap have no intermediate that can overflow, at any input, ever. xor_swap cannot overflow because XOR has no overflow case. It does not need a constraint to keep it honest.

What the compiler did with it

The panic is visible in the generated code, which is worth looking at because it is the whole argument for not writing the arithmetic version.

Here is xor_swap compiled without optimizations, on aarch64:

_xor_swap:
	eor	w8, w0, w1
	eor	w1, w8, w1
	eor	w0, w8, w1
	ret

Three instructions and a return. No branches, no flags to check, no call into the panic machinery.

Here is inplace_math from the same unoptimized build, trimmed:

_inplace_math:
	str	w1, [sp, #8]
	adds	w8, w0, w1
	cset	w8, vs
	tbnz	w8, #0, LBB2_2
	...
	bl	__RNvNtNtCs8Mbv00yxnRz_4core9panicking11panic_const24panic_const_add_overflow

The adds sets the overflow flag, cset reads it into a register, tbnz branches on it, and the branch target is the runtime’s panic handler. Every arithmetic operation in that function is followed by a check and a conditional call.

The debug profile is not adding safety to this code. It is adding the machinery to notice when this code is about to be wrong, at runtime, on every call.

All three are one program

The more interesting result is what happens with optimizations on. Compiling all three at -O, LLVM emits this body:

_inplace_math:
	mov	x8, x0
	mov	x0, x1
	mov	x1, x8
	ret

Three moves and a return. And then it goes further, emitting the other two as aliases of the same symbol:

	.globl	_tuple_swap
_tuple_swap = _inplace_math
	.globl	_xor_swap
_xor_swap = _inplace_math

The optimizer knows a ^ b ^ b == a, and it knows (a + b) - b == a. It folds both implementations into the tuple swap and then merges the three functions into one machine function. At -O, implicit_swap, inplace_math, and xor_swap are not three implementations that happen to agree. They are one implementation written three ways, and the compiler proves it.

Which means the XOR swap buys nothing. It is not faster than the tuple. It is not slower. It is the same three instructions, and the only thing it adds is the reader’s work.

The version that belongs in the crate

implicit_swap is the version that should be in the crate:

fn implicit_swap(a: i32, b: i32) -> (i32, i32) {
    (b, a)
}

No temporary variable, which is what the problem asked for. No overflow, so no input can make it panic. Nothing to reason about at the machine level because the machine level is not where the decision lives. The problem statement’s first hint says exactly this: in Rust you can simply return (b, a) as a tuple, the swap is implicit.

The function signature returns a tuple, so the swap is a value transformation, not a mutation. Rust made the mutation unnecessary by giving the signature a shape where both values can be returned at once. mem::swap exists for the cases where you really do need to mutate two places, and nothing here does.

I am keeping the other two in the file, and the file is better for it. The three of them together are the argument: the arithmetic version is the one that needs a constraint to stay safe, the XOR version is the one that needs a compiler to not cost anything, and the tuple version is the one that needs nothing.

A reader can see that the shipped choice was the least justified of the three, and the file still contains the reasons.

What I do now: when I catch myself writing XOR to avoid a temporary, I go read the disassembly before I keep it. Here it was three instructions, and they were the tuple’s.


Next: The Rounding That Did Not Round