TorchLean API

FloatLib.Kernels.LimbArray.Arithmetic.Runtime

Limb arrays: addition, subtraction, and multiplication #

The carry-propagating loops of multiple-precision integer arithmetic over LimbArray. Each loop recurses on the number of limbs still to process and writes its result with Array.setIfInBounds. The 32-bit limbs leave room for the addition and multiplication intermediates in UInt64.

Arithmetic.Proof states each kernel's effect on toNat, including the required capacity, borrow, and accumulator invariants.

Carry propagation #

Add carry at limb index and propagate upward through count limbs.

The loop stops as soon as the carry vanishes, so the common case touches one limb.

Instances For
    @[inline]

    Add the word w at limb index, discarding any carry beyond the stored array.

    Instances For

      Add w * 2^k to the array.

      The word is split at the limb boundary containing bit k; both halves are added with carry propagation. The result is meaningful when the sum still fits the stored limbs.

      Instances For

        Addition and subtraction #

        Add limbs index, index + 1, ... of two arrays into out, then store the final carry.

        Instances For

          The sum of two arrays and an incoming carry, in one limb more than the wider operand.

          Instances For

            Subtract limbs index, index + 1, ... of b and a borrow from those of a into out.

            Instances For

              The difference a - b - borrow, in as many limbs as the wider operand.

              The result is exact when borrow ≤ 1 and b + borrow ≤ a; Arithmetic.Proof.toNat_sub states that contract.

              Instances For

                Multiplication #

                Add m times count limbs of b, starting at limb j, into out at offset offset + j. Store the final carry at offset + j + count; that slot must initially be zero.

                Every intermediate m * b_j + out_(offset + j) + carry is below 2^64.

                Instances For

                  Accumulate count rows, starting with row i, each contributing a_i * b * 2^(32 i).

                  Instances For

                    The schoolbook product, in a.size + b.size limbs.

                    Instances For