Skip to content

Commit 29f8184

Browse files
committed
Add Display impl for RandomBitsError
1 parent 6dff8f6 commit 29f8184

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/traits.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ use subtle::{
2222
#[cfg(feature = "rand_core")]
2323
use rand_core::CryptoRngCore;
2424

25+
#[cfg(feature = "rand_core")]
26+
use core::fmt;
27+
2528
/// Integers whose representation takes a bounded amount of space.
2629
pub trait Bounded {
2730
/// Size of this integer in bits.
@@ -274,7 +277,7 @@ pub trait Random: Sized {
274277
fn random(rng: &mut impl CryptoRngCore) -> Self;
275278
}
276279

277-
/// Possible errors of [`RandomBits::try_random_bits`].
280+
/// Possible errors of the methods in [`RandomBits`] trait.
278281
#[cfg(feature = "rand_core")]
279282
#[derive(Debug)]
280283
pub enum RandomBitsError {
@@ -297,6 +300,37 @@ pub enum RandomBitsError {
297300
},
298301
}
299302

303+
#[cfg(feature = "rand_core")]
304+
impl fmt::Display for RandomBitsError {
305+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306+
match self {
307+
Self::RandCore(err) => write!(f, "{}", err),
308+
Self::BitsPrecisionMismatch {
309+
bits_precision,
310+
integer_bits,
311+
} => write!(
312+
f,
313+
concat![
314+
"The requested `bits_precision` ({}) does not match ",
315+
"the size of the integer corresponding to the type ({})"
316+
],
317+
bits_precision, integer_bits
318+
),
319+
Self::BitLengthTooLarge {
320+
bit_length,
321+
bits_precision,
322+
} => write!(
323+
f,
324+
"The requested `bit_length` ({}) is larger than `bits_precision` ({}).",
325+
bit_length, bits_precision
326+
),
327+
}
328+
}
329+
}
330+
331+
#[cfg(feature = "std")]
332+
impl std::error::Error for RandomBitsError {}
333+
300334
/// Random bits generation support.
301335
#[cfg(feature = "rand_core")]
302336
pub trait RandomBits: Sized {

0 commit comments

Comments
 (0)