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 rand_core::{Error, ErrorKind};
11use core::fmt;
12
13/// An error that can occur when [`JitterRng::test_timer`] fails.
14///
15/// [`JitterRng::test_timer`]: crate::JitterRng::test_timer
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum TimerError {
18    /// No timer available.
19    NoTimer,
20    /// Timer too coarse to use as an entropy source.
21    CoarseTimer,
22    /// Timer is not monotonically increasing.
23    NotMonotonic,
24    /// Variations of deltas of time too small.
25    TinyVariantions,
26    /// Too many stuck results (indicating no added entropy).
27    TooManyStuck,
28    #[doc(hidden)]
29    __Nonexhaustive,
30}
31
32impl TimerError {
33    fn description(&self) -> &'static str {
34        match *self {
35            TimerError::NoTimer => "no timer available",
36            TimerError::CoarseTimer => "coarse timer",
37            TimerError::NotMonotonic => "timer not monotonic",
38            TimerError::TinyVariantions => "time delta variations too small",
39            TimerError::TooManyStuck => "too many stuck results",
40            TimerError::__Nonexhaustive => unreachable!(),
41        }
42    }
43}
44
45impl fmt::Display for TimerError {
46    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47        write!(f, "{}", self.description())
48    }
49}
50
51#[cfg(feature = "std")]
52impl ::std::error::Error for TimerError {
53    fn description(&self) -> &str {
54        self.description()
55    }
56}
57
58impl From<TimerError> for Error {
59    fn from(err: TimerError) -> Error {
60        // Timer check is already quite permissive of failures so we don't
61        // expect false-positive failures, i.e. any error is irrecoverable.
62        Error::with_cause(ErrorKind::Unavailable,
63                              "timer jitter failed basic quality tests", err)
64    }
65}
66