Skip to main content

crypto_bigint/
checked.rs

1//! Checked arithmetic.
2
3use crate::UInt;
4use core::ops::{Add, AddAssign, Deref, Mul, MulAssign, Sub, SubAssign};
5use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
6
7/// Provides intentionally-checked arithmetic on `T`.
8///
9/// Internally this leverages the [`CtOption`] type from the [`subtle`] crate
10/// in order to handle overflows in constant time.
11#[derive(Copy, Clone, Debug)]
12pub struct Checked<T>(pub CtOption<T>);
13
14impl<T> Checked<T> {
15    /// Create a new checked arithmetic wrapper for the given value.
16    pub fn new(val: T) -> Self {
17        Self(CtOption::new(val, Choice::from(1)))
18    }
19}
20
21impl<T> Default for Checked<T>
22where
23    T: Default,
24{
25    fn default() -> Self {
26        Self::new(T::default())
27    }
28}
29
30impl<T> Deref for Checked<T> {
31    type Target = CtOption<T>;
32
33    fn deref(&self) -> &CtOption<T> {
34        &self.0
35    }
36}
37
38impl<T: ConditionallySelectable> ConditionallySelectable for Checked<T> {
39    #[inline]
40    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
41        Self(CtOption::conditional_select(&a.0, &b.0, choice))
42    }
43}
44
45impl<T: ConstantTimeEq> ConstantTimeEq for Checked<T> {
46    #[inline]
47    fn ct_eq(&self, rhs: &Self) -> Choice {
48        self.0.ct_eq(&rhs.0)
49    }
50}
51
52impl<const LIMBS: usize> Add for Checked<UInt<LIMBS>> {
53    type Output = Self;
54
55    fn add(self, rhs: Self) -> Checked<UInt<LIMBS>> {
56        Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_add(&b))))
57    }
58}
59
60impl<const LIMBS: usize> AddAssign for Checked<UInt<LIMBS>> {
61    fn add_assign(&mut self, other: Self) {
62        *self = *self + other;
63    }
64}
65
66impl<const LIMBS: usize> Sub for Checked<UInt<LIMBS>> {
67    type Output = Self;
68
69    fn sub(self, rhs: Self) -> Checked<UInt<LIMBS>> {
70        Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_sub(&b))))
71    }
72}
73
74impl<const LIMBS: usize> SubAssign for Checked<UInt<LIMBS>> {
75    fn sub_assign(&mut self, other: Self) {
76        *self = *self - other;
77    }
78}
79
80impl<const LIMBS: usize> Mul for Checked<UInt<LIMBS>> {
81    type Output = Self;
82
83    fn mul(self, rhs: Self) -> Checked<UInt<LIMBS>> {
84        Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_mul(&b))))
85    }
86}
87
88impl<const LIMBS: usize> MulAssign for Checked<UInt<LIMBS>> {
89    fn mul_assign(&mut self, other: Self) {
90        *self = *self * other;
91    }
92}