lurk-lab/lurk-rs

arithmetic with carry

Opened this issue · 0 comments

In order to be able to implement bignums in Lurk directly, we need support for multiplication with carry. Although we can detect overflow for addition, it would be better to have equivalent direct support.

I propose we add new variants of + and * that only work with u64 (and other UInt types, in the future). We might want a variant for - as well. Again, * is the urgent need.

I'll propose that we name these these operators *~, +~, and -~ but I'm open to other suggestions. These should return a pair of u64 values. The first value should be the same value as is returned by * and + respectively. The second should contain the 'carry' values or nil. The reason to prefer nil to an explicit 0u64 is to make checking for carry as cheap as possible.

See example usages with expected results:

user> (*~ (- 0u64 1u64) 123)
[? iterations] => (0xffffffffffffff85 . 122)

user> (*~ (- 0u64 1u64) 1u64)
[? iterations] => (0xffffffffffffffffu64)

user> (+~ (- 0u64 1u64) 10u64)
[? iterations] => (9u64 . 1)

user> (+~ 1u64 1u64)
[? iterations] => (2u64)

user> (-~ 10u64 1u64)
[? iterations] => (9u64)

user> (-~ 1u64 10u64)
[? iterations] => (0xfffffffffffffff7 . 1)