Skip to content

Commit

Permalink
impl core::error::Error for errors
Browse files Browse the repository at this point in the history
  • Loading branch information
fbernier committed Nov 27, 2024
1 parent 7f57304 commit 93eb348
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
[package]
name = "base62"
version = "2.0.3"
rust-version = "1.81.0"
authors = [
"François Bernier <[email protected]>",
"Chai T. Rex <[email protected]>",
"Kevin Darlington <[email protected]>",
"Christopher Tarquini <[email protected]>",
]
edition = "2018"
edition = "2021"
description = "A Base62 encoding/decoding library"
documentation = "https://docs.rs/base62/"
homepage = "https://github.com/fbernier/base62"
Expand Down
44 changes: 44 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ encoding to and decoding from [base62](https://en.wikipedia.org/wiki/Base62).

#![no_std]
extern crate alloc;

use alloc::string::String;

const BASE: u64 = 62;
Expand Down Expand Up @@ -67,6 +68,26 @@ impl core::fmt::Display for DecodeError {
}
}

impl core::error::Error for DecodeError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
None
}
}

impl core::fmt::Display for EncodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
EncodeError::BufferTooSmall => f.write_str("Buffer too small to encode number"),
}
}
}

impl core::error::Error for EncodeError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
None
}
}

/// Indicates the cause of an encoding failure in [`encode`](crate::encode_bytes).
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum EncodeError {
Expand Down Expand Up @@ -804,7 +825,10 @@ pub fn encode_alternative_buf<T: Into<u128>>(num: T, buf: &mut String) {
#[cfg(test)]
mod tests {
use super::*;
use alloc::boxed::Box;
use alloc::string::ToString;
use alloc::vec::Vec;
extern crate std;

// Don't run quickcheck tests under miri because that's infinitely slow
#[cfg(not(miri))]
Expand Down Expand Up @@ -1315,4 +1339,24 @@ mod tests {
assert_eq!(buf, "26Tf05FVsiGH0000000000");
// buf.clear();
}

#[test]
fn test_error_trait() {
fn assert_error<T: core::error::Error>(_: &T) {}

// Test that our errors implement Error
assert_error(&DecodeError::EmptyInput);
assert_error(&EncodeError::BufferTooSmall);
}

#[test]
fn test_std_error_compatibility() {
use std::error::Error;

let decode_err: Box<dyn Error> = Box::new(DecodeError::EmptyInput);
assert!(decode_err.to_string().contains("empty string"));

let encode_err: Box<dyn Error> = Box::new(EncodeError::BufferTooSmall);
assert!(encode_err.to_string().contains("Buffer too small"));
}
}

0 comments on commit 93eb348

Please sign in to comment.