Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support non-static lifetime inside error(transparent) #134

Merged
merged 2 commits into from May 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/aserror.rs
@@ -1,33 +1,33 @@
use std::error::Error;

pub trait AsDynError {
fn as_dyn_error(&self) -> &(dyn Error + 'static);
pub trait AsDynError<'a> {
fn as_dyn_error(&self) -> &(dyn Error + 'a);
}

impl<T: Error + 'static> AsDynError for T {
impl<'a, T: Error + 'a> AsDynError<'a> for T {
#[inline]
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
fn as_dyn_error(&self) -> &(dyn Error + 'a) {
self
}
}

impl AsDynError for dyn Error + 'static {
impl<'a> AsDynError<'a> for dyn Error + 'a {
#[inline]
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
fn as_dyn_error(&self) -> &(dyn Error + 'a) {
self
}
}

impl AsDynError for dyn Error + Send + 'static {
impl<'a> AsDynError<'a> for dyn Error + Send + 'a {
#[inline]
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
fn as_dyn_error(&self) -> &(dyn Error + 'a) {
self
}
}

impl AsDynError for dyn Error + Send + Sync + 'static {
impl<'a> AsDynError<'a> for dyn Error + Send + Sync + 'a {
#[inline]
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
fn as_dyn_error(&self) -> &(dyn Error + 'a) {
self
}
}
21 changes: 21 additions & 0 deletions tests/test_transparent.rs
Expand Up @@ -57,3 +57,24 @@ fn test_anyhow() {
assert_eq!("outer", error.to_string());
assert_eq!("inner", error.source().unwrap().to_string());
}

#[test]
fn test_non_static() {
#[derive(Error, Debug)]
#[error(transparent)]
struct Error<'a> {
inner: ErrorKind<'a>,
}

#[derive(Error, Debug)]
enum ErrorKind<'a> {
#[error("unexpected token: {:?}", token)]
Unexpected { token: &'a str },
}

let error = Error {
inner: ErrorKind::Unexpected { token: "error" },
};
assert_eq!("unexpected token: \"error\"", error.to_string());
assert!(error.source().is_none());
}