u1roh / warned-rs

Warned<T, W> type represents a value with warnings
2 stars 1 forks source link

Add `Option<T>` conversion utils #1

Open soywod opened 1 year ago

soywod commented 1 year ago

It could be nice to add function to unwrap an Option into a Warned, sth like:

Some(5).unwrap_or_warn("custom warn") // => Warned 5 vec![]
None.unwrap_or_warn("custom warn") // => Warned Default::default() vec!["custom warn"]
soywod commented 1 year ago

I got a working implementation:

pub trait UnwrapOrWarn<T, W> {
    fn unwrap_or_warn(self, warning: W) -> warned::Warned<T, W>;
}

impl<T: Default, W> UnwrapOrWarn<T, W> for Option<T> {
    fn unwrap_or_warn(self, warning: W) -> warned::Warned<T, W> {
        match self {
            Some(t) => warned::Warned::new(t, Vec::default()),
            None => warned::Warned::new(Default::default(), vec![warning]),
        }
    }
}