Simplify OptionalWrapper

- We never use `self`, so there is no need to pass it as a parameter...
- ... which then removes the need to instanciate the wrapper with `new`
- There is no reason to expect other type than `Option` so we can contrain
  the trait to the type directly instead of using the `IsOption` trait
This commit is contained in:
Nahor 2024-02-17 10:57:53 -08:00
parent 75fea0935e
commit bb7c9a5b9f
3 changed files with 9 additions and 22 deletions

View File

@ -108,7 +108,7 @@ impl Help {
Some(quote! {
Self::#ident #display_pat => {
use miette::macro_helpers::ToOption;
miette::macro_helpers::OptionalWrapper::<#ty>::new().to_option(&#help).as_ref().map(|#var| -> std::boxed::Box<dyn std::fmt::Display + '_> { std::boxed::Box::new(format!("{}", #var)) })
miette::macro_helpers::OptionalWrapper::<#ty>::to_option(&#help).as_ref().map(|#var| -> std::boxed::Box<dyn std::fmt::Display + '_> { std::boxed::Box::new(format!("{}", #var)) })
},
})
}
@ -137,7 +137,7 @@ impl Help {
#[allow(unused_variables, deprecated)]
let Self #display_pat = self;
use miette::macro_helpers::ToOption;
miette::macro_helpers::OptionalWrapper::<#ty>::new().to_option(&self.#member).as_ref().map(|#var| -> std::boxed::Box<dyn std::fmt::Display + '_> { std::boxed::Box::new(format!("{}", #var)) })
miette::macro_helpers::OptionalWrapper::<#ty>::to_option(&self.#member).as_ref().map(|#var| -> std::boxed::Box<dyn std::fmt::Display + '_> { std::boxed::Box::new(format!("{}", #var)) })
}
})
}

View File

@ -186,7 +186,7 @@ impl Labels {
};
Some(quote! {
miette::macro_helpers::OptionalWrapper::<#ty>::new().to_option(&self.#span)
miette::macro_helpers::OptionalWrapper::<#ty>::to_option(&self.#span)
.map(|#var| #ctor(
#display,
#var.clone(),
@ -273,7 +273,7 @@ impl Labels {
};
Some(quote! {
miette::macro_helpers::OptionalWrapper::<#ty>::new().to_option(#field)
miette::macro_helpers::OptionalWrapper::<#ty>::to_option(#field)
.map(|#var| #ctor(
#display,
#var.clone(),

View File

@ -3,38 +3,25 @@ use crate::protocol::{LabeledSpan, SourceSpan};
// Huge thanks to @jam1gamer for this hack:
// https://twitter.com/jam1garner/status/1515887996444323840
#[doc(hidden)]
pub trait IsOption {}
impl<T> IsOption for Option<T> {}
#[doc(hidden)]
#[derive(Debug, Default)]
pub struct OptionalWrapper<T>(pub core::marker::PhantomData<T>);
impl<T> OptionalWrapper<T> {
pub fn new() -> Self {
Self(core::marker::PhantomData)
}
}
#[doc(hidden)]
pub trait ToOption {
#[doc(hidden)]
fn to_option<T>(self, value: T) -> Option<T>;
fn to_option<T>(value: T) -> Option<T>;
}
impl<T> OptionalWrapper<T>
where
T: IsOption,
{
impl<T> OptionalWrapper<Option<T>> {
#[doc(hidden)]
pub fn to_option(self, value: &T) -> &T {
pub fn to_option(value: &Option<T>) -> &Option<T> {
value
}
}
impl<T> ToOption for &OptionalWrapper<T> {
fn to_option<U>(self, value: U) -> Option<U> {
impl<T> ToOption for OptionalWrapper<T> {
fn to_option<U>(value: U) -> Option<U> {
Some(value)
}
}