augmented_atomics/atomic_enum.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::marker::PhantomData;
24use std::sync::atomic::{AtomicUsize, Ordering};
25
26use num_traits::{FromPrimitive, ToPrimitive};
27
28/// Given an enum value deriving `FromPrimitive`/`ToPrimitive`, handles storing the value as an
29/// atomic usize.
30#[derive(Default, Debug)]
31pub struct AtomicEnum<Inner: FromPrimitive + ToPrimitive> {
32 value: AtomicUsize,
33 inner: PhantomData<Inner>,
34}
35
36impl<Inner: FromPrimitive + ToPrimitive> AtomicEnum<Inner> {
37 pub fn new(value: Inner) -> Self {
38 let value = value.to_usize().unwrap();
39 AtomicEnum {
40 value: AtomicUsize::new(value),
41 inner: PhantomData::default(),
42 }
43 }
44
45 #[inline]
46 pub fn set(&self, value: Inner) {
47 let value = value.to_usize().unwrap();
48 self.value.store(value, Ordering::Relaxed);
49 }
50
51 #[inline]
52 pub fn get(&self) -> Inner {
53 let value = self.value.load(Ordering::Relaxed);
54 Inner::from_usize(value).unwrap()
55 }
56}
57
58impl<Inner: FromPrimitive + ToPrimitive> From<Inner> for AtomicEnum<Inner> {
59 fn from(inner: Inner) -> Self {
60 Self::new(inner)
61 }
62}
63
64#[cfg(test)]
65mod test {
66 use num_derive::{FromPrimitive, ToPrimitive};
67
68 use super::*;
69
70 #[derive(FromPrimitive, ToPrimitive, Debug, PartialEq)]
71 enum TestEnum {
72 First,
73 Second,
74 Third,
75 }
76
77 #[test]
78 fn test_get_set_enum() {
79 let value = TestEnum::First;
80 let atomic_enum = AtomicEnum::new(value);
81 assert_eq!(atomic_enum.get(), TestEnum::First);
82 atomic_enum.set(TestEnum::Second);
83 assert_eq!(atomic_enum.get(), TestEnum::Second);
84 }
85}