tor-error: Introduce define_asref_dyn_std_error and use it

This factors out an ad-hoc AsRef impl.  We're going to want to reuse
this for another error type.
This commit is contained in:
Ian Jackson 2023-06-07 15:43:09 +01:00
parent f2f76f4f31
commit 33c90e5b72
2 changed files with 19 additions and 9 deletions

View File

@ -91,6 +91,23 @@ pub trait ErrorReport: StdError + Sized + 'static {
}
impl<E: StdError + Sized + 'static> ErrorReport for E {}
/// Defines `AsRef<dyn StdError + 'static>` for a type implementing [`StdError`]
///
/// This trivial `AsRef` impl enables use of `tor_error::Report`.
// Rust don't do this automatically, sadly, even though
// it's basically `impl AsRef<dyn Trait> for T where T: Trait`.
#[cfg(feature = "experimental-api")] // TODO HS make non-experimental, or rework
#[macro_export]
macro_rules! define_asref_dyn_std_error { { $ty:ty } => {
// TODO: It would nice if this could be generated more automatically;
// TODO wouldn't it be nice if this was a `derive` (eg using derive-adhoc)
impl AsRef<dyn std::error::Error + 'static> for $ty {
fn as_ref(&self) -> &(dyn std::error::Error + 'static) {
self as _
}
}
} }
#[cfg(test)]
mod test {
// @@ begin test lint list maintained by maint/add_warning @@

View File

@ -8,6 +8,7 @@ use tracing::error;
use retry_error::RetryError;
use safelog::Redacted;
use tor_error::define_asref_dyn_std_error;
use tor_error::{internal, Bug, ErrorKind, ErrorReport as _, HasKind};
use tor_llcrypto::pk::ed25519::Ed25519Identity;
@ -58,15 +59,7 @@ pub struct DescriptorError {
#[source]
pub error: DescriptorErrorDetail,
}
// This trivial AsRef impl enables use of `tor_error::Report`
// TODO: It would nice if this could be generated more automatically;
// it's basically `impl AsRef<dyn Trait> for T where T: Trait`.
impl AsRef<dyn std::error::Error + 'static> for DescriptorError {
fn as_ref(&self) -> &(dyn std::error::Error + 'static) {
self as _
}
}
define_asref_dyn_std_error!(DescriptorError);
/// Error that occurred attempting to download a descriptor
#[derive(Error, Clone, Debug)]