atomic-enums 0.2.0

Provides atomic enumerations.
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#![cfg_attr(not(test), no_std)]
//! This crate provides an `AtomicEnum`.
//! This can only be used with C like enumerations.
//!
//! The `gen_atomic_enum!` macro is provided which can be used to create a valid enumeration.
use core::fmt::Debug;
use core::marker::PhantomData;
use core::sync::atomic::{self, Ordering};

/// The trait must be implemented for enumerations which shall be used with an `AtomicEnum`.
/// Additionally the traits `Into<u16>` and `TryFrom<u16>` have to be implemented.
pub trait Atomize<T>: TryFrom<T> + Into<T> {}

/// This trait must be implemented for the underlying atomic type.
///
/// The trait is already implemented for:
/// - `AtomicU8`
/// - `AtomicU16`
/// - `AtomicU32`
/// - `AtomicU64` with the `u64` feature.
/// - `AtomicUsize` with the `usize` feature.
pub trait AtomicOps<T> {
    fn atomic_new(v: T) -> Self;

    fn atomic_load(&self, order: Ordering) -> T;

    fn atomic_store(&self, v: T, order: Ordering);

    fn atomic_swap(&self, v: T, order: Ordering) -> T;

    fn atomic_compare_exchange(
        &self,
        curr: T,
        new: T,
        success: Ordering,
        failure: Ordering,
    ) -> Result<T, T>;
}

/// The `AtomicEnum` is used to store values of an C like enumeration in
/// an atomic type.
pub struct AtomicEnum<E, A, U>(A, PhantomData<E>, PhantomData<U>);

impl<E, A, U> AtomicEnum<E, A, U>
where
    E: TryFrom<U> + Into<U>,
    A: AtomicOps<U>,
    U: Copy,
{
    /// Create a new atomic enumeration.
    ///
    /// ## Params
    /// - v: The value with which the enumeration is to be initialized
    ///
    /// ## Returns
    /// A new `AtomicEnum`
    ///
    /// ## Example
    /// ```
    /// use atomic_enums::{gen_atomic_enum, AtomicEnumU32};
    ///
    /// gen_atomic_enum!(State, u32:
    ///     Running: 2
    ///     Paused: 3
    /// );
    ///
    /// impl TryFrom<u32> for State {
    ///     type Error = ();
    ///
    ///     fn try_from(v: u32) -> Result<Self, Self::Error> {
    ///         match v {
    ///             2 => Ok(Self::Running),
    ///             3 => Ok(Self::Paused),
    ///             _ => Err(()),
    ///         }
    ///     }
    /// }
    ///
    /// let state = AtomicEnumU32::new(State::Running);
    ///  /* Do whatever you want to do... */
    /// ```
    pub fn new(v: E) -> Self {
        Self(A::atomic_new(v.into()), PhantomData, PhantomData)
    }

    /// Load the currently stored value of the atomic enum
    ///
    /// The following is copyed from the offical documentation of [`atomic::AtomicU32`].
    ///
    /// *`load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
    /// Possible values are [`Ordering::SeqCst`], [`Ordering::Acquire`] and [`Ordering::Relaxed`].*
    ///
    ///  ## Panics
    ///
    /// *Panics if `order` is [`Ordering::Release`] or [`Ordering::AcqRel`].*
    ///
    /// ## Example
    /// ```
    /// use atomic_enums::{gen_atomic_enum, AtomicEnumU32};
    ///
    /// use core::sync::atomic::Ordering::Relaxed;
    ///
    /// gen_atomic_enum!(State, u32:
    ///     Running: 2
    ///     Paused: 3
    /// );
    ///
    /// impl TryFrom<u32> for State {
    ///     type Error = ();
    ///
    ///     fn try_from(v: u32) -> Result<Self, Self::Error> {
    ///         match v {
    ///             2 => Ok(Self::Running),
    ///             3 => Ok(Self::Paused),
    ///             _ => Err(()),
    ///         }
    ///     }
    /// }
    ///
    /// let state = AtomicEnumU32::new(State::Paused);
    ///
    /// assert_eq!(state.load(Relaxed).unwrap(), State::Paused);
    /// ```
    pub fn load(&self, order: Ordering) -> Option<E> {
        match self.0.atomic_load(order).try_into() {
            Ok(e) => Some(e),
            Err(_) => None,
        }
    }

    /// Store the passed value in the atomic enumeration
    ///
    /// The following is copyed from the offical documentation of [`atomic::AtomicU32::store`].
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
    ///  
    /// *Possible values are [`Ordering::SeqCst`], [`Ordering::Release`] and [`Ordering::Relaxed`].*
    ///
    /// ## Panics
    ///
    /// *Panics if `order` is [`Ordering::Acquire`] or [`Ordering::AcqRel`].*
    ///
    /// ## Example
    /// ```
    /// use atomic_enums::{gen_atomic_enum, AtomicEnumU32};
    ///
    /// use core::sync::atomic::Ordering::Relaxed;
    ///
    /// gen_atomic_enum!(State, u32:
    ///     Running: 2
    ///     Paused: 3
    /// );
    ///
    /// impl TryFrom<u32> for State {
    ///     type Error = ();
    ///
    ///     fn try_from(v: u32) -> Result<Self, Self::Error> {
    ///         match v {
    ///             2 => Ok(Self::Running),
    ///             3 => Ok(Self::Paused),
    ///             _ => Err(()),
    ///         }
    ///     }
    /// }
    ///
    /// let state = AtomicEnumU32::new(State::Paused);
    ///
    /// state.store(State::Running, Relaxed);
    ///
    /// assert_eq!(state.load(Relaxed).unwrap(), State::Running);
    /// ```
    pub fn store(&self, val: E, order: Ordering) {
        self.0.atomic_store(val.into(), order)
    }

    /// Stores the passed enum value and returns the previous value.
    ///
    /// The following is copyed from the offical documentation of [`atomic::AtomicU32::swap`].
    ///
    /// *`swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Ordering::Acquire`] makes the store part of this operation [`Ordering::Relaxed`], and
    /// using [`Ordering::Release`] makes the load part [`Ordering::Relaxed`].*
    ///
    /// ## Example
    /// ```
    /// use atomic_enums::{gen_atomic_enum, AtomicEnumU32};
    ///
    /// use core::sync::atomic::Ordering::Relaxed;
    ///
    /// gen_atomic_enum!(State, u32:
    ///     Running: 2
    ///     Paused: 3
    /// );
    ///
    /// impl TryFrom<u32> for State {
    ///     type Error = ();
    ///
    ///     fn try_from(v: u32) -> Result<Self, Self::Error> {
    ///         match v {
    ///             2 => Ok(Self::Running),
    ///             3 => Ok(Self::Paused),
    ///             _ => Err(()),
    ///         }
    ///     }
    /// }
    ///
    /// let state = AtomicEnumU32::new(State::Paused);
    ///
    /// assert_eq!(state.swap(State::Running, Relaxed).unwrap(), State::Paused);
    /// assert_eq!(state.load(Relaxed).unwrap(), State::Running);
    /// ```
    pub fn swap(&self, val: E, order: Ordering) -> Option<E> {
        match self.0.atomic_swap(val.into(), order).try_into() {
            Ok(en) => Some(en),
            Err(_) => None,
        }
    }

    /// Stores the `new` value, if the `current` value ist equal to the currently stored value.
    ///
    /// The following is copyed from the offical documentation of [`atomic::AtomicU32::compare_exchange`].
    ///
    /// *The return value is a result indicating whether the new value was written and
    /// containing the previous value. On success this value is guaranteed to be equal to
    /// `current`.*
    ///
    /// *`compare_exchange` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. `success` describes the required ordering for the
    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
    /// `failure` describes the required ordering for the load operation that takes place when
    /// the comparison fails. Using [`Ordering::Acquire`] as success ordering makes the store part
    /// of this operation [`Ordering::Relaxed`], and using [`Ordering::Release`] makes the successful load
    /// [`Ordering::Relaxed`].
    /// The failure ordering can only be [`Ordering::SeqCst`], [`Ordering::Acquire`] or [`Ordering::Relaxed`].*
    ///
    /// ## Example
    /// ```
    /// use atomic_enums::{gen_atomic_enum, AtomicEnumU32};
    ///
    /// use core::sync::atomic::Ordering::Relaxed;
    ///
    /// gen_atomic_enum!(State, u32:
    ///     Running: 2
    ///     Paused: 3
    /// );
    ///
    /// impl TryFrom<u32> for State {
    ///     type Error = ();
    ///
    ///     fn try_from(v: u32) -> Result<Self, Self::Error> {
    ///         match v {
    ///             2 => Ok(Self::Running),
    ///             3 => Ok(Self::Paused),
    ///             _ => Err(()),
    ///         }
    ///     }
    /// }
    ///
    /// let state = AtomicEnumU32::new(State::Paused);
    ///
    /// let mut result = state.compare_exchange(
    ///     State::Paused,
    ///     State::Running,
    ///     Relaxed,
    ///     Relaxed,
    /// );
    /// assert_eq!(result.unwrap().unwrap(), State::Paused);
    ///
    /// result = state.compare_exchange(
    ///     State::Paused,
    ///     State::Running,
    ///     Relaxed,
    ///     Relaxed,
    /// );
    ///
    /// assert_eq!(result.unwrap_err().unwrap(), State::Running);
    /// ```
    pub fn compare_exchange(
        &self,
        current: E,
        new: E,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Option<E>, Option<E>> {
        match self
            .0
            .atomic_compare_exchange(current.into(), new.into(), success, failure)
        {
            Ok(v) => match v.try_into() {
                Ok(e) => Ok(Some(e)),
                Err(_) => Ok(None),
            },
            Err(v) => match v.try_into() {
                Ok(e) => Err(Some(e)),
                Err(_) => Err(None),
            },
        }
    }
}

impl<E, A, U> Debug for AtomicEnum<E, A, U>
where
    E: TryFrom<U> + Into<U> + Debug,
    A: AtomicOps<U>,
    U: Copy,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut dbg_info = f.debug_tuple("AtomicEnum");
        let tmp = self.load(Ordering::Relaxed);

        match tmp {
            Some(v) => dbg_info.field(&v),
            None => dbg_info.field(&"Invalid value!"),
        };

        dbg_info.finish()
    }
}

/// This macro can be used to generate a C like enumeration,
/// which automaticly implements `impl From<YourStruct> for <youre base type> { ... }` and `Atomize`.
/// You must implement the trait `impl TryFrom<youre base type> for YourStruct` to use the enumeration.
///
/// ## Params
/// 1. The name, which the enumeration
/// 2. The underlying type ([`u8`], [`u16`], [`u32`], [`u64`], [`usize`])
/// 3. List of, `EnumerationField`: `number`
///
/// ## Example
/// ```
/// use atomic_enums::gen_atomic_enum;
///
/// gen_atomic_enum!(State, u32:
///     Running: 2
///     Paused: 3
/// );
///
/// impl TryFrom<u32> for State {
///     type Error = ();
///
///     fn try_from(v: u32) -> Result<Self, Self::Error> {
///         match v {
///             2 => Ok(Self::Running),
///             3 => Ok(Self::Paused),
///             _ => Err(()),
///         }
///     }
/// }
///
/// assert_eq!(State::Running as u32, 2);
/// assert_eq!(State::Paused as u32, 3);
/// ```
#[macro_export]
macro_rules! gen_atomic_enum {
    ($name:ident, $b_ty:ty: $($val:ident: $num:expr)*) => {
        #[repr($b_ty)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum $name {
            $(
                $val = $num,
            )*
        }

        impl From<$name> for $b_ty {
            fn from(value: $name) -> Self {
                value as $b_ty
            }
        }

        impl atomic_enums::Atomize<$b_ty> for $name {}
    };
}

macro_rules! gen_atomic_ops_impls {
    ($($at:ty, $typ:ty, $name:ident)*) => {
        $(
            pub type $name<E> = AtomicEnum<E, $at, $typ>;

            impl AtomicOps<$typ> for $at {
                fn atomic_new(v: $typ) -> Self {
                    Self::new(v)
                }

                fn atomic_compare_exchange(&self, curr: $typ, new: $typ, success: Ordering, failure: Ordering) -> Result<$typ, $typ> {
                    self.compare_exchange(curr, new, success, failure)
                }

                fn atomic_load(&self, order: Ordering) -> $typ {
                    self.load(order)
                }

                fn atomic_store(&self, v: $typ, order: Ordering) {
                    self.store(v, order)
                }

                fn atomic_swap(&self, v: $typ, order: Ordering) -> $typ {
                    self.swap(v, order)
                }
            }
        )*
    };
}

gen_atomic_ops_impls!(
    atomic::AtomicU8, u8, AtomicEnumU8
    atomic::AtomicU16, u16, AtomicEnumU16
    atomic::AtomicU32, u32, AtomicEnumU32
    atomic::AtomicUsize, usize, AtomicEnumUsize
);

#[cfg(feature = "u64")]
gen_atomic_ops_impls!(atomic::AtomicU64, u64, AtomicEnumU64);

#[cfg(test)]
mod tests {
    use core::{
        marker::PhantomData,
        sync::atomic::Ordering::Relaxed,
    };

    use paste::item;

    use super::*;

    macro_rules! gen_tests {
        ($($bty:ty, $aty:ty, $abasety:ty)*) => {
            $(
                impl TryFrom<$bty> for TestEnum {
                    type Error = ();

                    fn try_from(value: $bty) -> Result<Self, Self::Error> {
                        match value {
                            1 => Ok(Self::Init),
                            2 => Ok(Self::Idle),
                            3 => Ok(Self::Running),
                            4 => Ok(Self::Stopped),
                            _ => Err(())
                        }
                    }
                }

                impl From<TestEnum> for $bty {
                    fn from(value: TestEnum) -> Self {
                        value as Self
                    }
                }

                item!{
                    #[test]
                    fn [<new_$bty>]() {
                        let new_enum = $aty::new(TestEnum::Init);

                        assert_eq!(new_enum.0.load(Relaxed), TestEnum::Init.into());
                    }

                    #[test]
                    fn [<load_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(TestEnum::Idle.into());

                        let result = test_enum.load(Relaxed);
                        assert!(result.is_some(), "Must return Some(TestEnum::Idle)");

                        let result = result.unwrap();
                        assert_eq!(result, TestEnum::Idle);
                    }

                    #[test]
                    fn [<store_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(TestEnum::Stopped.into());

                        test_enum.store(TestEnum::Idle, Relaxed);

                        assert_eq!(test_enum.0.load(Relaxed), TestEnum::Idle.into());
                    }

                    #[test]
                    fn [<cmp_exc_false_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(TestEnum::Running.into());

                        let result =
                            test_enum.compare_exchange(TestEnum::Idle, TestEnum::Running, Relaxed, Relaxed);
                        assert!(result.is_err());

                        let result = result.unwrap_err();
                        assert!(result.is_some());

                        let result = result.unwrap();
                        assert_eq!(result, TestEnum::Running);

                        assert_eq!(test_enum.0.load(Relaxed), TestEnum::Running.into())
                    }

                    #[test]
                    fn [<cmp_exc_true_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(TestEnum::Running.into());

                        let result =
                            test_enum.compare_exchange(TestEnum::Running, TestEnum::Idle, Relaxed, Relaxed);
                        assert!(result.is_ok());

                        let result = result.unwrap();
                        assert!(result.is_some());

                        let result = result.unwrap();
                        assert_eq!(result, TestEnum::Running);

                        assert_eq!(test_enum.0.load(Relaxed), TestEnum::Idle.into());
                    }

                    #[test]
                    fn [<swap_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(TestEnum::Init.into());

                        let result = test_enum.swap(TestEnum::Stopped, Relaxed);

                        assert!(result.is_some());

                        let result = result.unwrap();
                        assert_eq!(result, TestEnum::Init);

                        assert_eq!(test_enum.0.load(Relaxed), TestEnum::Stopped.into());
                    }

                    #[test]
                    fn [<load_invalid_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(32);

                        let result = test_enum.load(Relaxed);

                        assert!(result.is_none());
                    }

                    #[test]
                    fn [<swap_comp_invalid_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(255);

                        let result = test_enum.swap(TestEnum::Running, Relaxed);

                        assert!(result.is_none());
                        assert_eq!(test_enum.0.load(Relaxed), TestEnum::Running.into());
                    }

                    #[test]
                    fn [<compare_exchange_false_invalid_$bty>]() {
                        let test_enum: $aty<TestEnum> = init_enum(64);

                        let result = test_enum.compare_exchange(TestEnum::Running, TestEnum::Idle, Relaxed, Relaxed);

                        assert!(result.is_err());
                        assert!(result.unwrap_err().is_none());
                    }
                }
            )*
        };
    }

    fn init_enum<A: AtomicOps<U>, U>(val: U) -> AtomicEnum<TestEnum, A, U> {
        AtomicEnum {
            0: A::atomic_new(val),
            1: PhantomData,
            2: PhantomData,
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum TestEnum {
        Init = 1,
        Idle = 2,
        Running = 3,
        Stopped = 4,
    }

    gen_tests!(
        u8, AtomicEnumU8, atomic::AtomicU8
        u16, AtomicEnumU16, atomic::AtomicU16
        u32, AtomicEnumU32, atomic::AtomicU32
        usize, AtomicEnumUsize, atomic::AtomicUsize
    );

    #[cfg(feature = "u64")]
    gen_tests!(u64, AtomicEnumU64, atomic::AtomicU64);
}