ethnum/intrinsics/native/
sub.rs

1//! Module implementing subtraction intrinsics.
2
3use crate::{int::I256, uint::U256};
4use core::mem::MaybeUninit;
5
6#[inline]
7pub fn sub2(r: &mut U256, a: &U256) {
8    let (lo, carry) = r.low().overflowing_sub(*a.low());
9    *r.low_mut() = lo;
10    *r.high_mut() = r.high().wrapping_sub(carry as _).wrapping_sub(*a.high());
11}
12
13#[inline]
14pub fn sub3(r: &mut MaybeUninit<U256>, a: &U256, b: &U256) {
15    let (lo, carry) = a.low().overflowing_sub(*b.low());
16    let hi = a.high().wrapping_sub(carry as _).wrapping_sub(*b.high());
17
18    r.write(U256::from_words(hi, lo));
19}
20
21#[inline]
22pub fn usubc(r: &mut MaybeUninit<U256>, a: &U256, b: &U256) -> bool {
23    let (lo, carry_lo) = a.low().overflowing_sub(*b.low());
24    let (hi, carry_c) = a.high().overflowing_sub(carry_lo as _);
25    let (hi, carry_hi) = hi.overflowing_sub(*b.high());
26
27    r.write(U256::from_words(hi, lo));
28    carry_c || carry_hi
29}
30
31#[inline]
32pub fn isubc(r: &mut MaybeUninit<I256>, a: &I256, b: &I256) -> bool {
33    sub3(cast!(uninit: r), cast!(ref: a), cast!(ref: b));
34    let s = unsafe { r.assume_init_ref() };
35    (*b >= 0 && s > a) || (*b < 0 && s <= a)
36}