Skip to main content

Module bigint

Module bigint 

Source
Expand description

Arbitrary-precision integers, the engine’s BigInt.

A BigInt is a sign and a magnitude in base 2^32, little-endian, with no trailing zero words — so zero is the empty magnitude and every value has exactly one representation. That last part is what lets SameValueZero compare two BigInts with == and what lets a Map use one as a key.

§Two’s complement is the hard part

&, |, ^ and ~ are defined on the infinite two’s-complement form of the operand, which is why -1n & 3n is 3n and ~0n is -1n. The implementation converts to a fixed width of max(len(a), len(b)) + 1 words, does the operation there, and converts back; the extra word carries the sign extension so the result’s sign is recoverable.

>> is arithmetic: -1n >> 1n is -1n, not 0n. The shift is defined as floor(a / 2^n), which for a negative value is not a right shift of the magnitude — that rounds toward zero. The implementation does the magnitude shift and then corrects by subtracting one when any shifted-out bit was set.

§No dependency

There is no bignum crate available offline, so this is the arithmetic. It is deliberately the simplest correct algorithm at each step — schoolbook multiply, binary long division for the general case, divide-by-10^9 for decimal output — rather than the fastest.

Structs§

BigInt
An arbitrary-precision integer.