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
//! Track the number of extant instances of your types.
//! 
//! ## Example
//! ```
//! // 1. import these three items:
//! use type_census::{counter, Instance, Tabulate};
//! 
//! #[derive(Clone)]
//! pub struct Foo<T> {
//!     v: T,
//!     // 2. add a field of type `Instance<Self>`
//!     _instance: Instance<Self>,
//! }
//! 
//! impl<T> Foo<T>
//! {
//!     pub fn new(v: T) -> Self
//!     where
//!         // 3. add a `Self: Tabulate` bound to constructors
//!         Self: Tabulate,
//!     {
//!         Self {
//!             v,
//!             // 4. and initialize your `Instance` field like so:
//!             _instance: Instance::new(),
//!         }
//!     }
//! 
//!     pub fn v(self) -> T {
//!         self.v
//!     }
//! }
//! 
//! // 5. finally, implement `Tabulate` like this:
//! impl<T> Tabulate for Foo<T> {
//!     counter!();
//! }
//! 
//! fn main() {
//!     // you can now query the number of extant instances of `Foo`!
//!     assert_eq!(Foo::<i8>::instances(), 0);
//!     assert_eq!(Foo::<u8>::instances(), 0);
//! 
//!     // the same counter is shared for all generic instantiations
//!     let mut bar: Vec<Foo<i8>> = vec![Foo::new(0i8); 10];
//! 
//!     assert_eq!(Foo::<i8>::instances(), 10);
//!     assert_eq!(Foo::<u8>::instances(), 10);
//! 
//!     let _baz: Vec<Foo<u8>> = vec![Foo::new(0u8); 5];
//! 
//!     assert_eq!(Foo::<i8>::instances(), 15);
//!     assert_eq!(Foo::<u8>::instances(), 15);
//! 
//!     let _ = bar.drain(0..5);
//! 
//!     assert_eq!(Foo::<i8>::instances(), 10);
//!     assert_eq!(Foo::<u8>::instances(), 10);
//! }
//! ```

use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, Ordering};

/// A zero-sized guard that tracks the lifetime of an instance of `T`.
/// 
/// Constructing an `Instance<T>` increments the population count of `T`.
/// Dropping an `Instance<T>` decrements the population count of `T`. 
#[repr(transparent)]
pub struct Instance<T>
where
    T: Tabulate,
{
    _tabulated: PhantomData<T>,
}

impl<T> Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    pub fn new() -> Self
    {
        T::counter().fetch_add(1, Ordering::SeqCst);
        Instance {
            _tabulated: PhantomData,
        }
    }
}

impl<T> Clone for Instance<T>
where
    T: Tabulate
{
    #[inline(always)]
    fn clone(&self) -> Self {
        Self::new()
    }
}

impl<T> Drop for Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    fn drop(&mut self) {
        T::counter().fetch_sub(1, Ordering::SeqCst);
    }
}

impl<T> std::hash::Hash for Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
}

impl<T> Ord for Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    fn cmp(&self, _: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}

impl<T> PartialOrd for Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    fn partial_cmp(&self, _: &Self) -> Option<std::cmp::Ordering> {
        Some(std::cmp::Ordering::Equal)
    }
}

impl<T> Eq for Instance<T>
where
    T: Tabulate,
{}

impl<T> PartialEq for Instance<T>
where
    T: Tabulate,
{
    #[inline(always)]
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

/// Track the population of `Self`.
pub trait Tabulate: Sized {
    fn counter() -> &'static AtomicUsize;

    /// Produces the number of extant instances of `Self`.
    fn instances() -> usize
    where
        Self: 'static,
    {
        Self::counter().load(Ordering::SeqCst)
    }
}

/// Generates a correct implementation of [`Tabulate::counter`].
///
/// Use like:
/// ```
/// use type_census::{counter, Instance, Tabulate};
/// # pub struct Foo<T> { _v: T }
/// 
/// impl<T: 'static> Tabulate for Foo<T> {
///     counter!();
/// }
/// ```
#[macro_export]
macro_rules! counter {
    () => {
        fn counter() -> &'static std::sync::atomic::AtomicUsize {
            static COUNTER: std::sync::atomic::AtomicUsize = 
                std::sync::atomic::AtomicUsize::new(0);
            &COUNTER
        }
    };
}