hashes: Move FromSliceError to submodule

Add a public `error` module and move the one error for the `hashes`
crate into it.

Re-export at the crate root.

Done in preparation for adding an additional error type.
This commit is contained in:
Tobin C. Harding 2024-11-05 09:57:34 +11:00
parent 3b0cb0e87d
commit 5232bba62b
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
2 changed files with 31 additions and 24 deletions

29
hashes/src/error.rs Normal file
View File

@ -0,0 +1,29 @@
// SPDX-License-Identifier: CC0-1.0
//! Error code for the `hashes` crate.
use core::fmt;
/// Attempted to create a hash from an invalid length slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromSliceError {
pub(crate) expected: usize,
pub(crate) got: usize,
}
impl FromSliceError {
/// Returns the expected slice length.
pub fn expected_length(&self) -> usize { self.expected }
/// Returns the invalid slice length.
pub fn invalid_length(&self) -> usize { self.got }
}
impl fmt::Display for FromSliceError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid slice length {} (expected {})", self.got, self.expected)
}
}
#[cfg(feature = "std")]
impl std::error::Error for FromSliceError {}

View File

@ -96,6 +96,7 @@ pub mod _export {
mod internal_macros; mod internal_macros;
pub mod cmp; pub mod cmp;
pub mod error;
pub mod hash160; pub mod hash160;
pub mod hkdf; pub mod hkdf;
pub mod hmac; pub mod hmac;
@ -127,6 +128,7 @@ use core::{convert, fmt, hash};
#[rustfmt::skip] // Keep public re-exports separate. #[rustfmt::skip] // Keep public re-exports separate.
#[doc(inline)] #[doc(inline)]
pub use self::{ pub use self::{
error::FromSliceError,
hkdf::Hkdf, hkdf::Hkdf,
hmac::{Hmac, HmacEngine}, hmac::{Hmac, HmacEngine},
}; };
@ -317,30 +319,6 @@ fn incomplete_block_len<H: HashEngine>(eng: &H) -> usize {
(eng.n_bytes_hashed() % block_size) as usize (eng.n_bytes_hashed() % block_size) as usize
} }
/// Attempted to create a hash from an invalid length slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromSliceError {
expected: usize,
got: usize,
}
impl FromSliceError {
/// Returns the expected slice length.
pub fn expected_length(&self) -> usize { self.expected }
/// Returns the invalid slice length.
pub fn invalid_length(&self) -> usize { self.got }
}
impl fmt::Display for FromSliceError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid slice length {} (expected {})", self.got, self.expected)
}
}
#[cfg(feature = "std")]
impl std::error::Error for FromSliceError {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;