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
//! A module providing thread-safe and unsynchronized implementations for
//! Counters on various unsized integers.

use crate::{
    atomic::AtomicInt,
    clear::{Clear, Clearable},
    metric::Counter,
    num_wrapper::NumWrapper,
};
use std::cell::Cell;

macro_rules! impl_counter_for {
    ($int:path) => {
        impl Counter for Cell<$int> {
            fn incr_by(&self, count: usize) {
                let v = NumWrapper::<$int>::wrap(count);
                self.set(self.get().wrapping_add(v));
            }
        }

        impl Clear for Cell<$int> {
            fn clear(&self) {
                self.set(0);
            }
        }

        impl Clearable for Cell<$int> {
            fn is_cleared(&self) -> bool {
                self.get() == 0
            }
        }

        impl Counter for AtomicInt<$int> {
            fn incr_by(&self, count: usize) {
                let v = NumWrapper::<$int>::wrap(count);
                AtomicInt::<$int>::incr_by(&self, v);
            }
        }

        impl Clear for AtomicInt<$int> {
            fn clear(&self) {
                AtomicInt::<$int>::set(&self, 0);
            }
        }

        impl Clearable for AtomicInt<$int> {
            fn is_cleared(&self) -> bool {
                AtomicInt::<$int>::get(&self) == 0
            }
        }
    };
}

impl_counter_for!(u8);
impl_counter_for!(u16);
impl_counter_for!(u32);
impl_counter_for!(u64);
impl_counter_for!(u128);