rkyv_test/
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(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    /// Returns `true` if the option is a `None` value.
27    #[inline]
28    pub fn is_none(&self) -> bool {
29        match self {
30            ArchivedOption::None => true,
31            ArchivedOption::Some(_) => false,
32        }
33    }
34
35    /// Returns `true` if the option is a `Some` value.
36    #[inline]
37    pub fn is_some(&self) -> bool {
38        match self {
39            ArchivedOption::None => false,
40            ArchivedOption::Some(_) => true,
41        }
42    }
43
44    /// Converts to an `Option<&T>`.
45    #[inline]
46    pub const fn as_ref(&self) -> Option<&T> {
47        match self {
48            ArchivedOption::None => None,
49            ArchivedOption::Some(value) => Some(value),
50        }
51    }
52
53    /// Converts to an `Option<&mut T>`.
54    #[inline]
55    pub fn as_mut(&mut self) -> Option<&mut T> {
56        match self {
57            ArchivedOption::None => None,
58            ArchivedOption::Some(value) => Some(value),
59        }
60    }
61
62    /// Converts from `Pin<&ArchivedOption<T>>` to `Option<Pin<&T>>`.
63    #[inline]
64    pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
65        unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
66    }
67
68    /// Converts from `Pin<&mut ArchivedOption<T>>` to `Option<Pin<&mut T>>`.
69    #[inline]
70    pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
71        unsafe {
72            Pin::get_unchecked_mut(self)
73                .as_mut()
74                .map(|x| Pin::new_unchecked(x))
75        }
76    }
77
78    /// Returns an iterator over the possibly contained value.
79    #[inline]
80    pub const fn iter(&self) -> Iter<'_, T> {
81        Iter {
82            inner: self.as_ref(),
83        }
84    }
85
86    /// Returns a mutable iterator over the possibly contained value.
87    #[inline]
88    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
89        IterMut {
90            inner: self.as_mut(),
91        }
92    }
93
94    /// Inserts `v` into the option if it is `None`, then returns a mutable
95    /// reference to the contained value.
96    #[inline]
97    pub fn get_or_insert(&mut self, v: T) -> &mut T {
98        self.get_or_insert_with(move || v)
99    }
100
101    /// Inserts a value computed from `f` into the option if it is `None`, then
102    /// returns a mutable reference to the contained value.
103    #[inline]
104    pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
105        if let ArchivedOption::Some(ref mut value) = self {
106            value
107        } else {
108            *self = ArchivedOption::Some(f());
109            self.as_mut().unwrap()
110        }
111    }
112}
113
114impl<T: Deref> ArchivedOption<T> {
115    /// Converts from `&ArchivedOption<T>` to `Option<&T::Target>`.
116    ///
117    /// Leaves the original `ArchivedOption` in-place, creating a new one with a reference to the
118    /// original one, additionally coercing the contents via `Deref`.
119    #[inline]
120    pub fn as_deref(&self) -> Option<&<T as Deref>::Target> {
121        self.as_ref().map(|x| x.deref())
122    }
123}
124
125impl<T: DerefMut> ArchivedOption<T> {
126    /// Converts from `&mut ArchivedOption<T>` to `Option<&mut T::Target>`.
127    ///
128    /// Leaves the original `ArchivedOption` in-place, creating a new `Option` with a mutable
129    /// reference to the inner type's `Deref::Target` type.
130    #[inline]
131    pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target> {
132        self.as_mut().map(|x| x.deref_mut())
133    }
134}
135
136impl<T: Eq> Eq for ArchivedOption<T> {}
137
138impl<T: hash::Hash> hash::Hash for ArchivedOption<T> {
139    #[inline]
140    fn hash<H: hash::Hasher>(&self, state: &mut H) {
141        self.as_ref().hash(state)
142    }
143}
144
145impl<T: Ord> Ord for ArchivedOption<T> {
146    #[inline]
147    fn cmp(&self, other: &Self) -> cmp::Ordering {
148        self.as_ref().cmp(&other.as_ref())
149    }
150}
151
152impl<T: PartialEq> PartialEq for ArchivedOption<T> {
153    #[inline]
154    fn eq(&self, other: &Self) -> bool {
155        self.as_ref().eq(&other.as_ref())
156    }
157}
158
159impl<T: PartialOrd> PartialOrd for ArchivedOption<T> {
160    #[inline]
161    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
162        self.as_ref().partial_cmp(&other.as_ref())
163    }
164}
165
166impl<T, U: PartialEq<T>> PartialEq<Option<T>> for ArchivedOption<U> {
167    #[inline]
168    fn eq(&self, other: &Option<T>) -> bool {
169        if let ArchivedOption::Some(self_value) = self {
170            if let Some(other_value) = other {
171                self_value.eq(other_value)
172            } else {
173                false
174            }
175        } else {
176            other.is_none()
177        }
178    }
179}
180
181impl<T: PartialEq<U>, U> PartialEq<ArchivedOption<T>> for Option<U> {
182    #[inline]
183    fn eq(&self, other: &ArchivedOption<T>) -> bool {
184        other.eq(self)
185    }
186}
187
188/// An iterator over a reference to the `Some` variant of an `ArchivedOption`.
189///
190/// This iterator yields one value if the `ArchivedOption` is a `Some`, otherwise none.
191///
192/// This `struct` is created by the [`ArchivedOption::iter`] function.
193pub struct Iter<'a, T> {
194    pub(crate) inner: Option<&'a T>,
195}
196
197impl<'a, T> Iterator for Iter<'a, T> {
198    type Item = &'a T;
199
200    fn next(&mut self) -> Option<Self::Item> {
201        let mut result = None;
202        mem::swap(&mut self.inner, &mut result);
203        result
204    }
205}
206
207impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
208    fn next_back(&mut self) -> Option<Self::Item> {
209        self.next()
210    }
211}
212
213/// An iterator over a mutable reference to the `Some` variant of an `ArchivedOption`.
214///
215/// This iterator yields one value if the `ArchivedOption` is a `Some`, otherwise none.
216///
217/// This `struct` is created by the [`ArchivedOption::iter_mut`] function.
218pub struct IterMut<'a, T> {
219    pub(crate) inner: Option<&'a mut T>,
220}
221
222impl<'a, T> Iterator for IterMut<'a, T> {
223    type Item = &'a mut T;
224
225    fn next(&mut self) -> Option<Self::Item> {
226        let mut result = None;
227        mem::swap(&mut self.inner, &mut result);
228        result
229    }
230}
231
232impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
233    fn next_back(&mut self) -> Option<Self::Item> {
234        self.next()
235    }
236}