Skip to content

Commit

Permalink
Implement core/std::error::Error for error types (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
fbernier authored Jan 7, 2025
1 parent 317bb74 commit 3cc5e9c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ default = ["alloc"]
alloc = []
std = ["alloc"]

[dependencies]
rustversion = "1"

[dev-dependencies]
criterion = { version = "0.5", default-features = false }
quickcheck = "1"
Expand Down
33 changes: 29 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ pub enum DecodeError {
InvalidBase62Byte(u8, usize),
}

/// Indicates the cause of an encoding failure in [`encode`](crate::encode_bytes).
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum EncodeError {
BufferTooSmall,
}

impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
Expand All @@ -69,10 +75,29 @@ impl core::fmt::Display for DecodeError {
}
}

/// Indicates the cause of an encoding failure in [`encode`](crate::encode_bytes).
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum EncodeError {
BufferTooSmall,
// For DecodeError
#[rustversion::since(1.81)]
impl core::error::Error for DecodeError {}

#[rustversion::before(1.81)]
#[cfg(feature = "std")]
impl std::error::Error for DecodeError {}

// For EncodeError
#[rustversion::since(1.81)]
impl core::error::Error for EncodeError {}

#[rustversion::before(1.81)]
#[cfg(feature = "std")]
impl std::error::Error for EncodeError {}

// You'll also need to implement std::fmt::Display for EncodeError since it's required for Error
impl core::fmt::Display for EncodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
EncodeError::BufferTooSmall => write!(f, "Buffer too small to encode the number"),
}
}
}

/// Writes the base62 representation of a number using the standard alphabet to any fmt::Write destination.
Expand Down

0 comments on commit 3cc5e9c

Please sign in to comment.