1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#[cfg(feature = "std")]
use std_::error;
use std_::fmt;

use super::ResultLike;
use type_identity::TypeIdentity;

/// Extension trait for [Option].
pub trait OptionExt<T>: ResultLike + TypeIdentity<Type = Option<T>> + Sized {
    /// Allows using Option::filter before Rust 1.27.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::OptionExt;
    ///
    /// let text="what the ";
    ///
    /// assert_eq!(Some(text).filter_(|x| x.len()==9 ).is_some(),true);
    ///
    /// assert_eq!(
    ///     text.split_whitespace().next()
    ///         .filter_(|x| x.len()==4 ),
    ///     Some("what"));
    ///
    /// assert_eq!(Some(text).filter_(|x| x.len()==20 ),None);
    ///
    /// assert_eq!(
    ///     text.split_whitespace().next()
    ///         .filter_(|x| x.len()==10 ),
    ///     None);
    ///
    /// ```
    ///
    #[inline]
    fn filter_<F>(self, predicate: F) -> Option<T>
    where
        F: FnOnce(&T) -> bool,
    {
        if let Some(v) = self.into_type_val() {
            if predicate(&v) {
                return Some(v);
            }
        }
        None
    }
    /// Maps as reference to the contents.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::OptionExt;
    ///
    /// struct User{
    ///     name:String,
    ///     surname:String,
    /// }
    ///
    /// let user=Some(User{name:"Matt".into(),surname:"Parker".into()});
    /// let name   =user.map_ref(|v| v.name.as_str() );
    /// let surname=user.map_ref(|v| v.surname.as_str() );
    ///
    /// assert_eq!(name,Some("Matt"));
    /// assert_eq!(surname,Some("Parker"));
    ///
    /// ```
    #[inline]
    fn map_ref<'a, U, F>(&'a self, f: F) -> Option<U>
    where
        T: 'a,
        F: FnOnce(&'a T) -> U,
    {
        self.into_type_ref().as_ref().map(f)
    }
    /// Maps as mutable reference to the contents.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::OptionExt;
    ///
    /// struct User{
    ///     name:String,
    ///     surname:String,
    /// }
    ///
    /// let mut user=Some(User{name:"Matt".into(),surname:"Parker".into()});
    /// {
    ///     let name   =user.map_mut(|v|{
    ///         v.name.push_str("hew") ;
    ///         v.name.as_str()
    ///     });
    ///     
    ///     assert_eq!(name,Some("Matthew"));
    /// }
    /// assert_eq!(user.unwrap().name,"Matthew");
    ///
    /// ```
    #[inline]
    fn map_mut<'a, U, F>(&'a mut self, f: F) -> Option<U>
    where
        T: 'a,
        F: FnOnce(&'a mut T) -> U,
    {
        self.into_type_mut().as_mut().map(f)
    }
}

impl<T> OptionExt<T> for Option<T> {}

impl<T> ResultLike for Option<T> {
    type Item = T;
    type Error = IsNoneError;

    #[inline]
    fn is_item(&self) -> bool {
        self.is_some()
    }
    #[inline]
    fn to_result_(self) -> Result<Self::Item, Self::Error> {
        self.ok_or(IsNoneError)
    }
}

////////////////////////////////////////////////////////////////////////////////////

/// The [ResultLike::Error]
/// value for Option<T>
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct IsNoneError;

impl fmt::Display for IsNoneError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("attempted to unwrap an Option that was None")
    }
}

#[cfg(feature = "std")]
impl error::Error for IsNoneError {
    fn description(&self) -> &str {
        "attempted to unwrap an Option that was None"
    }
}

////////////////////////////////////////////////////////////////////////////////////

/// Converts a type containing options into an option containing the type
pub trait ToOption {
    /// The type in which the `Option`s are unwrapped.
    ///
    /// Example:
    /// Self==(Option<i32>,Option<i32>)
    /// type Output=(i32,i32);
    type Output;
    /// Performs the conversion
    fn to_option(self) -> Option<Self::Output>;
}

impl<T> ToOption for Option<T> {
    type Output = T;
    fn to_option(self) -> Option<Self::Output> {
        self
    }
}

impl<T> ToOption for (Option<T>, Option<T>) {
    type Output = (T, T);

    fn to_option(self) -> Option<Self::Output> {
        Some((try_opt!(self.0), try_opt!(self.1)))
    }
}

impl<T> ToOption for (Option<T>, Option<T>, Option<T>) {
    type Output = (T, T, T);

    fn to_option(self) -> Option<Self::Output> {
        Some((try_opt!(self.0), try_opt!(self.1), try_opt!(self.2)))
    }
}

impl<T> ToOption for (Option<T>, Option<T>, Option<T>, Option<T>) {
    type Output = (T, T, T, T);

    fn to_option(self) -> Option<Self::Output> {
        Some((
            try_opt!(self.0),
            try_opt!(self.1),
            try_opt!(self.2),
            try_opt!(self.3),
        ))
    }
}

impl<T> ToOption for (Option<T>, Option<T>, Option<T>, Option<T>, Option<T>) {
    type Output = (T, T, T, T, T);

    fn to_option(self) -> Option<Self::Output> {
        Some((
            try_opt!(self.0),
            try_opt!(self.1),
            try_opt!(self.2),
            try_opt!(self.3),
            try_opt!(self.4),
        ))
    }
}