augmented_atomics/atomic_option.rs
1// Augmented Audio: Audio libraries and applications
2// Copyright (c) 2022 Pedro Tacla Yamada
3//
4// The MIT License (MIT)
5//
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12//
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15//
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22// THE SOFTWARE.
23use std::sync::atomic::{AtomicBool, Ordering};
24
25use crate::AtomicValue;
26
27pub struct AtomicOption<T: AtomicValue + Default> {
28 is_present: AtomicBool,
29 value: T,
30}
31
32impl<T: AtomicValue + Default> AtomicOption<T> {
33 pub fn new(value: T) -> Self {
34 Self {
35 is_present: AtomicBool::new(true),
36 value,
37 }
38 }
39
40 pub fn empty() -> Self {
41 Self {
42 is_present: AtomicBool::new(false),
43 value: Default::default(),
44 }
45 }
46
47 #[inline]
48 pub fn set(&self, value: Option<T::Inner>) {
49 if let Some(value) = value {
50 self.value.set(value);
51 self.is_present.store(true, Ordering::Relaxed);
52 } else {
53 self.is_present.store(false, Ordering::Relaxed);
54 }
55 }
56
57 #[inline]
58 pub fn inner(&self) -> Option<T::Inner> {
59 let is_present = self.is_present.load(Ordering::Relaxed);
60 if is_present {
61 Some(self.value.get())
62 } else {
63 None
64 }
65 }
66}
67
68impl<T: AtomicValue + Default + From<T::Inner>> From<Option<T::Inner>> for AtomicOption<T> {
69 fn from(value: Option<T::Inner>) -> Self {
70 if let Some(value) = value {
71 Self::new(value.into())
72 } else {
73 Self::empty()
74 }
75 }
76}