From 93eb34863157e1cf58902d539b404eb8930bc5ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Bernier?= Date: Tue, 19 Nov 2024 00:15:51 -0500 Subject: [PATCH] impl core::error::Error for errors --- Cargo.toml | 3 ++- src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 10a182c..2489998 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,14 @@ [package] name = "base62" version = "2.0.3" +rust-version = "1.81.0" authors = [ "François Bernier ", "Chai T. Rex ", "Kevin Darlington ", "Christopher Tarquini ", ] -edition = "2018" +edition = "2021" description = "A Base62 encoding/decoding library" documentation = "https://docs.rs/base62/" homepage = "https://github.com/fbernier/base62" diff --git a/src/lib.rs b/src/lib.rs index f0b01a6..1823a1e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; @@ -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 { @@ -804,7 +825,10 @@ pub fn encode_alternative_buf>(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))] @@ -1315,4 +1339,24 @@ mod tests { assert_eq!(buf, "26Tf05FVsiGH0000000000"); // buf.clear(); } + + #[test] + fn test_error_trait() { + fn assert_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 = Box::new(DecodeError::EmptyInput); + assert!(decode_err.to_string().contains("empty string")); + + let encode_err: Box = Box::new(EncodeError::BufferTooSmall); + assert!(encode_err.to_string().contains("Buffer too small")); + } }