rand_jitter/error.rs
1// Copyright 2018 Developers of the Rand project.
2// Copyright 2013-2015 The Rust Project Developers.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use core::fmt;
11
12/// Base code for all `JitterRng` errors
13const ERROR_BASE: u32 = 0xAE53_0400;
14
15/// An error that can occur when [`JitterRng::test_timer`] fails.
16///
17/// All variants have a value of 0xAE530400 = 2924676096 plus a small
18/// increment (1 through 5).
19///
20/// [`JitterRng::test_timer`]: crate::JitterRng::test_timer
21#[derive(Debug, Clone, PartialEq, Eq)]
22#[repr(u32)]
23#[allow(clippy::manual_non_exhaustive)]
24//^ TODO: Replace with `#[non_exhaustive]` for Rust >= 1.40
25pub enum TimerError {
26 /// No timer available.
27 NoTimer = ERROR_BASE + 1,
28 /// Timer too coarse to use as an entropy source.
29 CoarseTimer = ERROR_BASE + 2,
30 /// Timer is not monotonically increasing.
31 NotMonotonic = ERROR_BASE + 3,
32 /// Variations of deltas of time too small.
33 TinyVariations = ERROR_BASE + 4,
34 /// Too many stuck results (indicating no added entropy).
35 TooManyStuck = ERROR_BASE + 5,
36 #[doc(hidden)]
37 __Nonexhaustive,
38}
39
40impl TimerError {
41 fn description(&self) -> &'static str {
42 match *self {
43 TimerError::NoTimer => "no timer available",
44 TimerError::CoarseTimer => "coarse timer",
45 TimerError::NotMonotonic => "timer not monotonic",
46 TimerError::TinyVariations => "time delta variations too small",
47 TimerError::TooManyStuck => "too many stuck results",
48 TimerError::__Nonexhaustive => unreachable!(),
49 }
50 }
51}
52
53impl fmt::Display for TimerError {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 write!(f, "{}", self.description())
56 }
57}
58
59#[cfg(feature = "std")]
60impl ::std::error::Error for TimerError {
61 fn description(&self) -> &str {
62 self.description()
63 }
64}