orx_concurrent_option/
with_order.rs

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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use crate::{states::*, ConcurrentOption};
use core::{ops::Deref, sync::atomic::Ordering};

impl<T> ConcurrentOption<T> {
    /// Loads and returns the concurrent state of the option with the given `order`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::some(2);
    /// assert_eq!(x.state(Ordering::Relaxed), State::Some);
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::none();
    /// assert_eq!(x.state(Ordering::SeqCst), State::None);
    /// ```
    pub fn state(&self, order: Ordering) -> State {
        State::new(self.state.load(order))
    }

    /// Returns `true` if the option is a Some variant.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::some(2);
    /// assert_eq!(x.is_some(), true);
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::none();
    /// assert_eq!(x.is_some(), false);
    /// ```
    #[inline]
    pub fn is_some_with_order(&self, order: Ordering) -> bool {
        self.state.load(order) == SOME
    }

    /// Returns `true` if the option is a None variant.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_concurrent_option::*;
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::some(2);
    /// assert_eq!(x.is_none(), false);
    ///
    /// let x: ConcurrentOption<u32> = ConcurrentOption::none();
    /// assert_eq!(x.is_none(), true);
    /// ```
    #[inline]
    pub fn is_none_with_order(&self, order: Ordering) -> bool {
        self.state.load(order) != SOME
    }

    /// Converts from `&Option<T>` to `Option<&T>`.
    ///
    /// Depending on requirement of the use case, `Relaxed`, `Acquire` or `SeqCst` can be used as the `order`.
    ///
    /// # Safety
    ///
    /// Note that creating a valid reference part of this method is thread safe.
    ///
    /// The method is `unsafe` due to the returned reference to the underlying value.
    ///
    /// * It is safe to use this method if the returned reference is discarded (miri would still complain).
    /// * It is also safe to use this method if the caller is able to guarantee that there exist
    /// no concurrent writes while holding onto this reference.
    ///   * One such case is using `as_ref` together with `initialize_when_none` method.
    /// This is perfectly safe since the value will be written only once,
    /// and `as_ref` returns a valid reference only after the value is initialized.
    /// * Otherwise, it will lead to an **Undefined Behavior** due to data race.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// let x = ConcurrentOption::some(3.to_string());
    /// assert_eq!(unsafe { x.as_ref_with_order(Ordering::Relaxed) }, Some(&3.to_string()));
    ///
    /// _ = x.take();
    /// assert_eq!(unsafe { x.as_ref_with_order(Ordering::Acquire) }, None);
    /// ```
    pub unsafe fn as_ref_with_order(&self, order: Ordering) -> Option<&T> {
        match self.state.load(order) {
            SOME => {
                let x = &*self.value.get();
                Some(x.assume_init_ref())
            }
            _ => None,
        }
    }

    /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
    ///
    /// Leaves the original Option in-place, creating a new one with a reference
    /// to the original one, additionally coercing the contents via [`Deref`].
    ///
    /// Depending on requirement of the use case, `Relaxed`, `Acquire` or `SeqCst` can be used as the `order`.
    ///
    /// # Safety
    ///
    /// Note that creating a valid reference part of this method is thread safe.
    ///
    /// The method is `unsafe` due to the returned reference to the underlying value.
    ///
    /// * It is safe to use this method if the returned reference is discarded (miri would still complain).
    /// * It is also safe to use this method if the caller is able to guarantee that there exist
    /// no concurrent writes while holding onto this reference.
    ///   * One such case is using `as_ref` together with `initialize_when_none` method.
    /// This is perfectly safe since the value will be written only once,
    /// and `as_ref` returns a valid reference only after the value is initialized.
    /// * Otherwise, it will lead to an **Undefined Behavior** due to data race.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// unsafe
    /// {
    ///     let x: ConcurrentOption<String> = ConcurrentOption::some("hey".to_owned());
    ///     assert_eq!(x.as_deref_with_order(Ordering::Acquire), Some("hey"));
    ///
    ///     let x: ConcurrentOption<String> = ConcurrentOption::none();
    ///     assert_eq!(x.as_deref_with_order(Ordering::SeqCst), None);
    /// }
    /// ```
    pub unsafe fn as_deref_with_order(&self, order: Ordering) -> Option<&<T as Deref>::Target>
    where
        T: Deref,
    {
        match self.state.load(order) {
            SOME => {
                let x = &*self.value.get();
                Some(x.assume_init_ref())
            }
            _ => None,
        }
    }

    /// Returns an iterator over the possibly contained value; yields
    /// * the single element if the option is of Some variant;
    /// * no elements otherwise.
    ///
    /// Depending on requirement of the use case, `Relaxed`, `Acquire` or `SeqCst` can be used as the `order`.
    ///
    /// # Safety
    ///
    /// Note that creating a valid reference part of this method is thread safe.
    ///
    /// The method is `unsafe` due to the returned reference to the underlying value.
    ///
    /// * It is safe to use this method if the returned reference is discarded (miri would still complain).
    /// * It is also safe to use this method if the caller is able to guarantee that there exist
    /// no concurrent writes while holding onto this reference.
    ///   * One such case is using `as_ref` together with `initialize_when_none` method.
    /// This is perfectly safe since the value will be written only once,
    /// and `as_ref` returns a valid reference only after the value is initialized.
    /// * Otherwise, it will lead to an **Undefined Behavior** due to data race.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// fn validate<'a>(mut iter: impl ExactSizeIterator<Item = &'a String>) {
    ///     assert_eq!(iter.len(), 0);
    ///     assert!(iter.next().is_none());
    ///     assert!(iter.next().is_none());
    /// }
    ///
    /// let x = ConcurrentOption::<String>::none();
    /// unsafe
    /// {
    /// validate(x.iter_with_order(Ordering::SeqCst));
    ///     validate(x.iter_with_order(Ordering::Relaxed).rev());
    ///     validate((&x).into_iter());
    /// }
    /// ```
    pub unsafe fn iter_with_order(&self, order: Ordering) -> crate::iter::Iter<'_, T> {
        let maybe = unsafe { self.as_ref_with_order(order) };
        crate::iter::Iter { maybe }
    }

    /// Clones the concurrent option with the desired `order` into an Option.
    ///
    /// Note that the `Clone` trait implementation clones the concurrent option with the default ordering.
    ///
    /// You may use `clone_with_order` in order to clone with the desired ordering.
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// let mut x = ConcurrentOption::some(42);
    /// let y = x.clone_with_order(Ordering::SeqCst);
    /// assert_eq!(x.take(), y);
    /// ```
    pub fn clone_with_order(&self, order: Ordering) -> Option<T>
    where
        T: Clone,
    {
        unsafe { self.as_ref_with_order(order) }.cloned()
    }

    /// Returns whether or not self is equal to the `other` with the desired `order`.
    ///
    /// Note that the `PartialEq` trait implementation checks equality with the default ordering.
    ///
    /// You may use `eq_with_order` in order to check equality with the desired ordering.
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::sync::atomic::Ordering;
    ///
    /// let x = ConcurrentOption::some(3);
    /// let y = ConcurrentOption::some(7);
    /// let z = ConcurrentOption::<i32>::none();
    ///
    /// let o = Ordering::SeqCst;
    ///
    /// assert!(x.eq_with_order(&x, o));
    /// assert!(!x.eq_with_order(&y, o));
    /// assert!(!x.eq_with_order(&z, o));
    ///
    /// assert!(!z.eq_with_order(&x, o));
    /// assert!(!z.eq_with_order(&y, o));
    /// assert!(z.eq_with_order(&z, o));
    /// ```
    pub fn eq_with_order(&self, other: &Self, order: Ordering) -> bool
    where
        T: PartialEq,
    {
        match (unsafe { self.as_ref_with_order(order) }, unsafe {
            other.as_ref_with_order(order)
        }) {
            (None, None) => true,
            (Some(x), Some(y)) => x.eq(y),
            _ => false,
        }
    }

    /// Returns an ordering between `self` and `other` with the desired `order`.
    ///
    /// Note that the `PartialOrd` trait implementation checks equality with the default ordering.
    ///
    /// You may use `partial_cmp_with_order` in order to check equality with the desired ordering.
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::cmp::Ordering::*;
    ///
    /// let x = ConcurrentOption::some(3);
    /// let y = ConcurrentOption::some(7);
    /// let z = ConcurrentOption::<i32>::none();
    ///
    /// let ord = core::sync::atomic::Ordering::SeqCst;
    ///
    /// assert_eq!(x.partial_cmp_with_order(&x, ord), Some(Equal));
    /// assert_eq!(x.partial_cmp_with_order(&y, ord), Some(Less));
    /// assert_eq!(x.partial_cmp_with_order(&z, ord), Some(Greater));
    ///
    /// assert_eq!(y.partial_cmp_with_order(&x, ord), Some(Greater));
    /// assert_eq!(y.partial_cmp_with_order(&y, ord), Some(Equal));
    /// assert_eq!(y.partial_cmp_with_order(&z, ord), Some(Greater));
    ///
    /// assert_eq!(z.partial_cmp_with_order(&x, ord), Some(Less));
    /// assert_eq!(z.partial_cmp_with_order(&y, ord), Some(Less));
    /// assert_eq!(z.partial_cmp_with_order(&z, ord), Some(Equal));
    /// ```
    pub fn partial_cmp_with_order(
        &self,
        other: &Self,
        order: Ordering,
    ) -> Option<core::cmp::Ordering>
    where
        T: PartialOrd,
    {
        use core::cmp::Ordering::*;

        match (unsafe { self.as_ref_with_order(order) }, unsafe {
            other.as_ref_with_order(order)
        }) {
            (Some(l), Some(r)) => l.partial_cmp(r),
            (Some(_), None) => Some(Greater),
            (None, Some(_)) => Some(Less),
            (None, None) => Some(Equal),
        }
    }

    /// Returns an ordering between `self` and `other` with the desired `order`.
    ///
    /// Note that the `Ord` trait implementation checks equality with the default ordering.
    ///
    /// You may use `cmp_with_order` in order to check equality with the desired ordering.
    ///
    /// ```rust
    /// use orx_concurrent_option::*;
    /// use core::cmp::Ordering::*;
    ///
    /// let x = ConcurrentOption::some(3);
    /// let y = ConcurrentOption::some(7);
    /// let z = ConcurrentOption::<i32>::none();
    ///
    /// let ord = core::sync::atomic::Ordering::SeqCst;
    ///
    /// assert_eq!(x.cmp_with_order(&x, ord), Equal);
    /// assert_eq!(x.cmp_with_order(&y, ord), Less);
    /// assert_eq!(x.cmp_with_order(&z, ord), Greater);
    ///
    /// assert_eq!(y.cmp_with_order(&x, ord), Greater);
    /// assert_eq!(y.cmp_with_order(&y, ord), Equal);
    /// assert_eq!(y.cmp_with_order(&z, ord), Greater);
    ///
    /// assert_eq!(z.cmp_with_order(&x, ord), Less);
    /// assert_eq!(z.cmp_with_order(&y, ord), Less);
    /// assert_eq!(z.cmp_with_order(&z, ord), Equal);
    /// ```
    pub fn cmp_with_order(&self, other: &Self, order: Ordering) -> core::cmp::Ordering
    where
        T: Ord,
    {
        use core::cmp::Ordering::*;

        match (unsafe { self.as_ref_with_order(order) }, unsafe {
            other.as_ref_with_order(order)
        }) {
            (Some(l), Some(r)) => l.cmp(r),
            (Some(_), None) => Greater,
            (None, Some(_)) => Less,
            (None, None) => Equal,
        }
    }
}