NFC: Polyfill const_option feature.

This commit is contained in:
Brian Smith 2022-10-28 21:21:59 -07:00
parent 901441fd59
commit 301f31671b
3 changed files with 22 additions and 19 deletions

View File

@ -35,7 +35,9 @@ mod leading_zeros_skipped;
#[cfg(test)]
mod test;
pub use self::{array_flat_map::ArrayFlatMap, chunks_fixed::*};
mod unwrap_const;
pub use self::{array_flat_map::ArrayFlatMap, chunks_fixed::*, unwrap_const::unwrap_const};
#[cfg(feature = "alloc")]
pub use leading_zeros_skipped::LeadingZerosStripped;

View File

@ -0,0 +1,15 @@
/// Polyfill for `Option::unwrap()` as a const fn; feature `const_option`.
/// https://github.com/rust-lang/rust/issues/67441.
/// TODO(MSRV): Replace this with `x.unwrap()`.
///
/// `T: Copy` avoids "constant functions cannot evaluate destructors."
pub const fn unwrap_const<T>(x: Option<T>) -> T
where
T: Copy,
{
if let Some(x) = x {
x
} else {
panic!("unwrap_const on `None`");
}
}

View File

@ -1,5 +1,5 @@
use crate::error;
use crate::polyfill::{ArrayFlatMap, LeadingZerosStripped};
use crate::polyfill::{unwrap_const, ArrayFlatMap, LeadingZerosStripped};
use core::num::NonZeroU64;
/// The exponent `e` of an RSA public key.
@ -10,16 +10,8 @@ impl PublicExponent {
#[cfg(test)]
const ALL_CONSTANTS: [Self; 3] = [Self::_3, Self::_65537, Self::MAX];
// TODO: Use `NonZeroU64::new(...).unwrap()` when `feature(const_panic)` is
// stable.
pub(super) const _3: Self = Self(match NonZeroU64::new(3) {
Some(nz) => nz,
None => unreachable!(),
});
pub(super) const _65537: Self = Self(match NonZeroU64::new(65537) {
Some(nz) => nz,
None => unreachable!(),
});
pub(super) const _3: Self = Self(unwrap_const(NonZeroU64::new(3)));
pub(super) const _65537: Self = Self(unwrap_const(NonZeroU64::new(65537)));
// This limit was chosen to bound the performance of the simple
// exponentiation-by-squaring implementation in `elem_exp_vartime`. In
@ -32,13 +24,7 @@ impl PublicExponent {
// [1] https://www.imperialviolet.org/2012/03/16/rsae.html
// [2] https://www.imperialviolet.org/2012/03/17/rsados.html
// [3] https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
//
// TODO: Use `NonZeroU64::new(...).unwrap()` when `feature(const_panic)` is
// stable.
const MAX: Self = Self(match NonZeroU64::new((1u64 << 33) - 1) {
Some(nz) => nz,
None => unreachable!(),
});
const MAX: Self = Self(unwrap_const(NonZeroU64::new((1u64 << 33) - 1)));
pub(super) fn from_be_bytes(
input: untrusted::Input,