orx_concurrent_option/common_traits/clone.rs
1use crate::{ConcurrentOption, states::SOME};
2
3impl<T: Clone> Clone for ConcurrentOption<T> {
4 /// Clones the concurrent option with the [`Relaxed`] ordering.
5 ///
6 /// In order to clone with a stronger ordering,
7 /// you may call [`clone_with_order`] with the desired ordering.
8 ///
9 /// [`Relaxed`]: core::sync::atomic::Ordering::Relaxed
10 /// [`clone_with_order`]: ConcurrentOption::clone_with_order
11 ///
12 /// ```rust
13 /// use orx_concurrent_option::*;
14 /// use core::sync::atomic::Ordering;
15 ///
16 /// let x = ConcurrentOption::some(42);
17 /// let y = x.clone(); // clone with default Relaxed ordering
18 /// assert_eq!(x, y);
19 ///
20 /// let x = ConcurrentOption::some(42);
21 /// let y = x.clone_with_order(Ordering::SeqCst).into(); // clone with desired ordering SeqCst
22 /// assert_eq!(x, y);
23 /// ```
24 fn clone(&self) -> Self {
25 // hold the lock for the entire clone; `as_ref` alone would release it before `x.clone()` runs
26 match self.spin_get_handle(SOME, SOME) {
27 Some(_handle) => {
28 let x = unsafe { (*self.value.get()).assume_init_ref() };
29 Self::some(x.clone())
30 }
31 None => Self::none(),
32 }
33 }
34}