Skip to main content

crypto_bigint/
limb.rs

1//! Big integers are represented as an array of smaller CPU word-size integers
2//! called "limbs".
3
4#![allow(clippy::derive_hash_xor_eq)]
5
6mod add;
7mod bit_and;
8mod bit_or;
9mod cmp;
10mod encoding;
11mod from;
12mod mul;
13mod sub;
14
15#[cfg(feature = "rand")]
16mod rand;
17
18use core::fmt;
19use subtle::{Choice, ConditionallySelectable};
20
21#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
22compile_error!("this crate builds on 32-bit and 64-bit platforms only");
23
24//
25// 32-bit definitions
26//
27
28/// Size of the inner integer in bits.
29#[cfg(target_pointer_width = "32")]
30pub const BIT_SIZE: usize = 32;
31
32/// Size of the inner integer in bytes.
33#[cfg(target_pointer_width = "32")]
34pub const BYTE_SIZE: usize = 4;
35
36/// Inner integer type that the [`Limb`] newtype wraps.
37#[cfg(target_pointer_width = "32")]
38pub type Inner = u32;
39
40/// Wide integer type: double the width of [`Inner`].
41#[cfg(target_pointer_width = "32")]
42pub type Wide = u64;
43
44//
45// 64-bit definitions
46//
47
48/// Size of the inner integer in bits.
49#[cfg(target_pointer_width = "64")]
50pub const BIT_SIZE: usize = 64;
51
52/// Size of the inner integer in bytes.
53#[cfg(target_pointer_width = "64")]
54pub const BYTE_SIZE: usize = 8;
55
56/// Inner integer type that the [`Limb`] newtype wraps.
57#[cfg(target_pointer_width = "64")]
58pub type Inner = u64;
59
60/// Wide integer type: double the width of [`Inner`].
61#[cfg(target_pointer_width = "64")]
62pub type Wide = u128;
63
64/// Big integers are represented as an array of smaller CPU word-size integers
65/// called "limbs".
66#[derive(Copy, Clone, Debug, Default, Hash)]
67#[repr(transparent)]
68pub struct Limb(pub Inner);
69
70impl Limb {
71    /// The value `0`.
72    pub const ZERO: Self = Limb(0);
73
74    /// The value `1`.
75    pub const ONE: Self = Limb(1);
76
77    /// Maximum value this [`Limb`] can express.
78    pub const MAX: Self = Limb(Inner::MAX);
79}
80
81impl ConditionallySelectable for Limb {
82    #[inline]
83    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
84        Limb(Inner::conditional_select(&a.0, &b.0, choice))
85    }
86}
87
88impl fmt::Display for Limb {
89    #[inline]
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        fmt::UpperHex::fmt(self, f)
92    }
93}
94
95impl fmt::LowerHex for Limb {
96    #[inline]
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        fmt::LowerHex::fmt(&self.0, f)
99    }
100}
101
102impl fmt::UpperHex for Limb {
103    #[inline]
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        fmt::UpperHex::fmt(&self.0, f)
106    }
107}
108
109#[cfg(feature = "zeroize")]
110#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
111impl zeroize::DefaultIsZeroes for Limb {}