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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use crate::Bool;
use std::fmt::{Debug, Formatter};

#[repr(C)]
#[derive(Copy, Clone)]
union OptionalImpl<T>
where
    T: Copy + Sized,
{
    val: T,
    dummy: i8,
}

impl<T> OptionalImpl<T>
where
    T: Copy + Sized,
{
    pub fn new_value(val: T) -> Self {
        Self { val }
    }

    pub fn new_empty() -> Self {
        Self { dummy: 0 }
    }

    pub fn value(&self) -> T {
        unsafe { self.val }
    }

    pub fn value_ref(&self) -> &T {
        unsafe { &self.val }
    }
}

/// A type containing an optional value.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Optional<T>
where
    T: Copy + Sized,
{
    data: OptionalImpl<T>,
    has_value: Bool,
}

impl<T> Optional<T>
where
    T: Copy + Sized,
{
    /// Creates a new `Optional<T>` containing the value.
    pub fn some(val: T) -> Self {
        Self {
            data: OptionalImpl::new_value(val),
            has_value: Bool::True,
        }
    }

    /// Creates an empty `Optional<T>`.
    pub fn none() -> Self {
        Self {
            data: OptionalImpl::new_empty(),
            has_value: Bool::False,
        }
    }

    /// Returns `true` if the optional contains a value.
    pub fn is_some(&self) -> bool {
        self.has_value == Bool::True
    }

    /// Returns `true` if the optional is empty.
    pub fn is_none(&self) -> bool {
        self.has_value == Bool::False
    }

    /// Maps the `Optional<T>` to `Optional<&T>`.
    pub fn as_ref(&self) -> Optional<&T> {
        match self.is_some() {
            true => Optional::some(self.data.value_ref()),
            false => Optional::none(),
        }
    }

    /// Maps the `Optional<T>` to `Option<T>`.
    pub fn to_option(self) -> Option<T> {
        self.map_or(Option::None, Some)
    }

    /// Returns the contained value.
    ///
    /// # Panics
    ///
    /// Panics if no value is contained with a custom panic message provided by `msg`.
    pub fn expect(self, msg: &str) -> T {
        match self.is_some() {
            true => self.data.value(),
            false => panic!("{}", msg),
        }
    }

    /// Returns the contained value.
    ///
    /// # Panics
    ///
    /// Panics if no value is contained.
    pub fn unwrap(self) -> T {
        match self.is_some() {
            true => self.data.value(),
            false => panic!("called `Optional::unwrap()` on an empty optional"),
        }
    }

    /// Returns the contained value or a default.
    pub fn unwrap_or(self, default: T) -> T {
        match self.is_some() {
            true => self.data.value(),
            false => default,
        }
    }

    /// Returns the contained value or computes it from a closure.
    pub fn unwrap_or_else<F>(self, f: F) -> T
    where
        F: FnOnce() -> T,
    {
        match self.is_some() {
            true => self.data.value(),
            false => f(),
        }
    }

    /// Maps an `Optional<T>` to `Optional<U>` by applying a function to the contained value.
    pub fn map<U, F>(self, f: F) -> Optional<U>
    where
        U: Copy + Sized,
        F: FnOnce(T) -> U,
    {
        match self.is_some() {
            true => Optional::some(f(self.data.value())),
            false => Optional::none(),
        }
    }

    /// Returns the application of the closure to the contained value or a default value.
    pub fn map_or<U, F>(self, default: U, f: F) -> U
    where
        F: FnOnce(T) -> U,
    {
        match self.is_some() {
            true => f(self.data.value()),
            false => default,
        }
    }

    /// Applies a function to the contained value (if any), or computes a default (if not).
    pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
    where
        D: FnOnce() -> U,
        F: FnOnce(T) -> U,
    {
        match self.is_some() {
            true => f(self.data.value()),
            false => default(),
        }
    }

    /// Transforms the `Optional<T>` into a `Result<T, E>`.
    pub fn ok_or<E>(self, err: E) -> crate::collections::Result<T, E>
    where
        E: Copy + Sized,
    {
        match self.is_some() {
            true => crate::collections::Result::new_ok(self.data.value()),
            false => crate::collections::Result::new_err(err),
        }
    }

    /// Transforms the `Optional<T>` into a `Result<T, E>` by mapping the contained value or
    /// computing an error value from a closure.
    pub fn ok_or_else<E, F>(self, f: F) -> crate::collections::Result<T, E>
    where
        E: Copy + Sized,
        F: FnOnce() -> E,
    {
        match self.is_some() {
            true => crate::collections::Result::new_ok(self.data.value()),
            false => crate::collections::Result::new_err(f()),
        }
    }
}

impl<T> Debug for Optional<T>
where
    T: Copy + Sized + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.is_some() {
            true => write!(f, "Some({:?})", self.data.value()),
            false => write!(f, "None"),
        }
    }
}

impl<T> Default for Optional<T>
where
    T: Copy + Sized,
{
    fn default() -> Self {
        Self::none()
    }
}

impl<T> PartialEq for Optional<T>
where
    T: Copy + Sized + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.is_some() == other.is_some()
            && (!self.is_some() || self.data.value_ref() == other.data.value_ref())
    }
}

impl<T> Eq for Optional<T> where T: Copy + Sized + PartialEq + Eq {}

impl<T> From<Option<T>> for Optional<T>
where
    T: Copy + Sized,
{
    fn from(opt: Option<T>) -> Self {
        opt.map_or_else(Optional::none, Optional::some)
    }
}

impl<T> From<Optional<T>> for Option<T>
where
    T: Copy + Sized,
{
    fn from(opt: Optional<T>) -> Self {
        opt.to_option()
    }
}