nim-stint/stint/private/uint_addsub.nim

58 lines
1.7 KiB
Nim
Raw Normal View History

# Stint
# Copyright 2018-Present Status Research & Development GmbH
# Licensed under either of
#
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
#
# at your option. This file may not be copied, modified, or distributed except according to those terms.
import
# Internal
./datatypes,
./primitives/addcarry_subborrow
# Addsub
# --------------------------------------------------------
2023-06-12 14:07:15 +00:00
{.push raises: [], inline, noinit, gcsafe.}
2023-06-12 14:07:15 +00:00
func sum*(r: var StUint, a, b: StUint) =
## Addition for multi-precision unsigned int
var carry = Carry(0)
for i in 0 ..< r.limbs.len:
addC(carry, r[i], a[i], b[i], carry)
r.clearExtraBitsOverMSB()
2023-06-12 14:07:15 +00:00
func `+=`*(a: var StUint, b: StUint) =
## In-place addition for multi-precision unsigned int
a.sum(a, b)
2023-06-12 14:07:15 +00:00
func diff*(r: var StUint, a, b: StUint) =
## Substraction for multi-precision unsigned int
var borrow = Borrow(0)
for i in 0 ..< r.limbs.len:
subB(borrow, r[i], a[i], b[i], borrow)
r.clearExtraBitsOverMSB()
2023-06-12 14:07:15 +00:00
func `-=`*(a: var StUint, b: StUint) =
## In-place substraction for multi-precision unsigned int
a.diff(a, b)
2023-06-12 14:07:15 +00:00
func inc*(a: var StUint, w: Word = 1) =
var carry = Carry(0)
addC(carry, a.limbs[0], a.limbs[0], w, carry)
for i in 1 ..< a.limbs.len:
addC(carry, a.limbs[i], a.limbs[i], 0, carry)
a.clearExtraBitsOverMSB()
2023-06-12 14:07:15 +00:00
func sum*(r: var StUint, a: StUint, b: SomeUnsignedInt) =
## Addition for multi-precision unsigned int
## with an unsigned integer
r = a
r.inc(Word(b))
2023-06-12 14:07:15 +00:00
func `+=`*(a: var StUint, b: SomeUnsignedInt) =
## In-place addition for multi-precision unsigned int
## with an unsigned integer
a.inc(Word(b))