Skip to main content

crypto_bigint/limb/
from.rs

1//! `From`-like conversions for [`Limb`].
2
3use super::{Limb, WideWord, Word};
4
5impl Limb {
6    /// Create a [`Limb`] from a `u8` integer (const-friendly)
7    // TODO(tarcieri): replace with `const impl From<u8>` when stable
8    #[must_use]
9    pub const fn from_u8(n: u8) -> Self {
10        Limb(n as Word)
11    }
12
13    /// Create a [`Limb`] from a `u16` integer (const-friendly)
14    // TODO(tarcieri): replace with `const impl From<u16>` when stable
15    #[must_use]
16    pub const fn from_u16(n: u16) -> Self {
17        Limb(n as Word)
18    }
19
20    /// Create a [`Limb`] from a `u32` integer (const-friendly)
21    // TODO(tarcieri): replace with `const impl From<u32>` when stable
22    #[must_use]
23    pub const fn from_u32(n: u32) -> Self {
24        #[allow(trivial_numeric_casts)]
25        Limb(n as Word)
26    }
27
28    cpubits::cpubits! {
29        64 => {
30            /// Create a [`Limb`] from a `u64` integer (const-friendly)
31            // TODO(tarcieri): replace with `const impl From<u64>` when stable
32            #[must_use]
33            pub const fn from_u64(n: u64) -> Self {
34                Limb(n)
35            }
36        }
37    }
38}
39
40impl From<u8> for Limb {
41    #[inline]
42    fn from(n: u8) -> Limb {
43        Limb(n.into())
44    }
45}
46
47impl From<u16> for Limb {
48    #[inline]
49    fn from(n: u16) -> Limb {
50        Limb(n.into())
51    }
52}
53
54impl From<u32> for Limb {
55    #[inline]
56    fn from(n: u32) -> Limb {
57        Limb(n.into())
58    }
59}
60
61impl From<u64> for Limb {
62    #[inline]
63    fn from(n: u64) -> Limb {
64        cpubits::cpubits! {
65            32 => {
66                let overflow = (n >> 32) as u32;
67                assert!(Limb(overflow).is_zero().to_bool());
68                Limb(n as u32)
69            }
70            64 => {
71                Limb(n)
72            }
73        }
74    }
75}
76
77impl From<Limb> for Word {
78    #[inline]
79    fn from(limb: Limb) -> Word {
80        limb.0
81    }
82}
83
84impl From<Limb> for WideWord {
85    #[inline]
86    fn from(limb: Limb) -> WideWord {
87        limb.0.into()
88    }
89}