xkcp_rs/
error.rs

1use core::fmt;
2
3/// Keccak result type alias.
4pub type Result<T, E = Error> = core::result::Result<T, E>;
5
6/// Keccak errors.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum Error {
9    /// Generic failure.
10    Fail,
11    /// The provided output buffer is too small.
12    OutputTooSmall,
13}
14
15#[cfg(feature = "std")]
16impl std::error::Error for Error {}
17
18impl fmt::Display for Error {
19    #[inline]
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        f.write_str(match self {
22            Error::Fail => "generic failure",
23            Error::OutputTooSmall => "output buffer too small",
24        })
25    }
26}
27
28impl Error {
29    /// Converts a raw [`HashReturn`](ffi::HashReturn) value into a [`Result`].
30    #[inline]
31    pub fn from_raw(raw: ffi::HashReturn) -> Result<()> {
32        match raw {
33            ffi::HashReturn::KECCAK_SUCCESS => Ok(()),
34            ffi::HashReturn::KECCAK_FAIL => Err(Error::Fail),
35            ffi::HashReturn::KECCAK_BAD_HASHLEN => Err(Error::OutputTooSmall),
36        }
37    }
38
39    /// Converts a raw integer return value into a [`Result`].
40    #[inline]
41    pub fn from_int(raw: i32) -> Result<()> {
42        if raw == 0 {
43            Ok(())
44        } else {
45            Err(Error::Fail)
46        }
47    }
48}