rkyv/
option.rs

1//! An archived version of `Option`.
2
3use core::{
4    cmp, hash,
5    iter::DoubleEndedIterator,
6    mem,
7    ops::{Deref, DerefMut},
8    pin::Pin,
9};
10
11/// An archived [`Option`].
12///
13/// It functions identically to [`Option`] but has a different internal
14/// representation to allow for archiving.
15#[derive(Clone, Copy, Debug)]
16#[cfg_attr(feature = "validation", derive(bytecheck::CheckBytes))]
17#[repr(u8)]
18pub enum ArchivedOption<T> {
19    /// No value
20    None,
21    /// Some value `T`
22    Some(T),
23}
24
25impl<T> ArchivedOption<T> {
26    /// Transforms the `ArchivedOption<T>` into a `Result<T, E>`, mapping `Some(v)` to `Ok(v)` and
27    /// `None` to `Err(err)`.
28    pub fn ok_or<E>(self, err: E) -> Result<T, E> {
29        match self {
30            ArchivedOption::None => Err(err),
31            ArchivedOption::Some(x) => Ok(x),
32        }
33    }
34    /// Returns the contained [`Some`] value, consuming the `self` value.
35    pub fn unwrap(self) -> T {
36        match self {
37            ArchivedOption::None => panic!("called `ArchivedOption::unwrap()` on a `None` value"),
38            ArchivedOption::Some(value) => value,
39        }
40    }
41    /// Returns the contained [`Some`] value or a provided default.
42    pub fn unwrap_or(self, default: T) -> T {
43        match self {
44            ArchivedOption::None => default,
45            ArchivedOption::Some(value) => value,
46        }
47    }
48    /// Returns the contained [`Some`] value or computes it from a closure.
49    pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
50        match self {
51            ArchivedOption::None => f(),
52            ArchivedOption::Some(value) => value,
53        }
54    }
55    /// Returns `true` if the option is a `None` value.
56    #[inline]
57    pub fn is_none(&self) -> bool {
58        match self {
59            ArchivedOption::None => true,
60            ArchivedOption::Some(_) => false,
61        }
62    }
63
64    /// Returns `true` if the option is a `Some` value.
65    #[inline]
66    pub fn is_some(&self) -> bool {
67        match self {
68            ArchivedOption::None => false,
69            ArchivedOption::Some(_) => true,
70        }
71    }
72
73    /// Converts to an `Option<&T>`.
74    #[inline]
75    pub const fn as_ref(&self) -> Option<&T> {
76        match self {
77            ArchivedOption::None => None,
78            ArchivedOption::Some(value) => Some(value),
79        }
80    }
81
82    /// Converts to an `Option<&mut T>`.
83    #[inline]
84    pub fn as_mut(&mut self) -> Option<&mut T> {
85        match self {
86            ArchivedOption::None => None,
87            ArchivedOption::Some(value) => Some(value),
88        }
89    }
90
91    /// Converts from `Pin<&ArchivedOption<T>>` to `Option<Pin<&T>>`.
92    #[inline]
93    pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
94        unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
95    }
96
97    /// Converts from `Pin<&mut ArchivedOption<T>>` to `Option<Pin<&mut T>>`.
98    #[inline]
99    pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
100        unsafe {
101            Pin::get_unchecked_mut(self)
102                .as_mut()
103                .map(|x| Pin::new_unchecked(x))
104        }
105    }
106
107    /// Returns an iterator over the possibly contained value.
108    #[inline]
109    pub const fn iter(&self) -> Iter<'_, T> {
110        Iter {
111            inner: self.as_ref(),
112        }
113    }
114
115    /// Returns a mutable iterator over the possibly contained value.
116    #[inline]
117    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
118        IterMut {
119            inner: self.as_mut(),
120        }
121    }
122
123    /// Inserts `v` into the option if it is `None`, then returns a mutable
124    /// reference to the contained value.
125    #[inline]
126    pub fn get_or_insert(&mut self, v: T) -> &mut T {
127        self.get_or_insert_with(move || v)
128    }
129
130    /// Inserts a value computed from `f` into the option if it is `None`, then
131    /// returns a mutable reference to the contained value.
132    #[inline]
133    pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
134        if let ArchivedOption::Some(ref mut value) = self {
135            value
136        } else {
137            *self = ArchivedOption::Some(f());
138            self.as_mut().unwrap()
139        }
140    }
141}
142
143impl<T: Deref> ArchivedOption<T> {
144    /// Converts from `&ArchivedOption<T>` to `Option<&T::Target>`.
145    ///
146    /// Leaves the original `ArchivedOption` in-place, creating a new one with a reference to the
147    /// original one, additionally coercing the contents via `Deref`.
148    #[inline]
149    pub fn as_deref(&self) -> Option<&<T as Deref>::Target> {
150        self.as_ref().map(|x| x.deref())
151    }
152}
153
154impl<T: DerefMut> ArchivedOption<T> {
155    /// Converts from `&mut ArchivedOption<T>` to `Option<&mut T::Target>`.
156    ///
157    /// Leaves the original `ArchivedOption` in-place, creating a new `Option` with a mutable
158    /// reference to the inner type's `Deref::Target` type.
159    #[inline]
160    pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target> {
161        self.as_mut().map(|x| x.deref_mut())
162    }
163}
164
165impl<T: Eq> Eq for ArchivedOption<T> {}
166
167impl<T: hash::Hash> hash::Hash for ArchivedOption<T> {
168    #[inline]
169    fn hash<H: hash::Hasher>(&self, state: &mut H) {
170        self.as_ref().hash(state)
171    }
172}
173
174impl<T: Ord> Ord for ArchivedOption<T> {
175    #[inline]
176    fn cmp(&self, other: &Self) -> cmp::Ordering {
177        self.as_ref().cmp(&other.as_ref())
178    }
179}
180
181impl<T: PartialEq> PartialEq for ArchivedOption<T> {
182    #[inline]
183    fn eq(&self, other: &Self) -> bool {
184        self.as_ref().eq(&other.as_ref())
185    }
186}
187
188impl<T: PartialOrd> PartialOrd for ArchivedOption<T> {
189    #[inline]
190    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
191        self.as_ref().partial_cmp(&other.as_ref())
192    }
193}
194
195impl<T, U: PartialEq<T>> PartialEq<Option<T>> for ArchivedOption<U> {
196    #[inline]
197    fn eq(&self, other: &Option<T>) -> bool {
198        if let ArchivedOption::Some(self_value) = self {
199            if let Some(other_value) = other {
200                self_value.eq(other_value)
201            } else {
202                false
203            }
204        } else {
205            other.is_none()
206        }
207    }
208}
209
210impl<T: PartialEq<U>, U> PartialEq<ArchivedOption<T>> for Option<U> {
211    #[inline]
212    fn eq(&self, other: &ArchivedOption<T>) -> bool {
213        other.eq(self)
214    }
215}
216
217impl<T> From<T> for ArchivedOption<T> {
218    /// Moves `val` into a new [`Some`].
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// # use rkyv::option::ArchivedOption;
224    /// let o: ArchivedOption<u8> = ArchivedOption::from(67);
225    ///
226    /// assert_eq!(Some(67), o);
227    /// ```
228    fn from(val: T) -> ArchivedOption<T> {
229        ArchivedOption::Some(val)
230    }
231}
232
233/// An iterator over a reference to the `Some` variant of an `ArchivedOption`.
234///
235/// This iterator yields one value if the `ArchivedOption` is a `Some`, otherwise none.
236///
237/// This `struct` is created by the [`ArchivedOption::iter`] function.
238pub struct Iter<'a, T> {
239    pub(crate) inner: Option<&'a T>,
240}
241
242impl<'a, T> Iterator for Iter<'a, T> {
243    type Item = &'a T;
244
245    fn next(&mut self) -> Option<Self::Item> {
246        let mut result = None;
247        mem::swap(&mut self.inner, &mut result);
248        result
249    }
250}
251
252impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
253    fn next_back(&mut self) -> Option<Self::Item> {
254        self.next()
255    }
256}
257
258/// An iterator over a mutable reference to the `Some` variant of an `ArchivedOption`.
259///
260/// This iterator yields one value if the `ArchivedOption` is a `Some`, otherwise none.
261///
262/// This `struct` is created by the [`ArchivedOption::iter_mut`] function.
263pub struct IterMut<'a, T> {
264    pub(crate) inner: Option<&'a mut T>,
265}
266
267impl<'a, T> Iterator for IterMut<'a, T> {
268    type Item = &'a mut T;
269
270    fn next(&mut self) -> Option<Self::Item> {
271        let mut result = None;
272        mem::swap(&mut self.inner, &mut result);
273        result
274    }
275}
276
277impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
278    fn next_back(&mut self) -> Option<Self::Item> {
279        self.next()
280    }
281}