derive_relaxedcounter/
derive-relaxedcounter.rs

1// 1. import these two items:
2use type_census::{Instance, Tabulate};
3
4// 2. Derive `Tabulate`
5// This will count instances with `RelaxedCounter`.
6#[derive(Clone, Tabulate)]
7pub struct Foo<T> {
8    v: T,
9    // 3. add a field of type `Instance<Self>`
10    _instance: Instance<Self>,
11}
12
13impl<T> Foo<T> {
14    pub fn new(v: T) -> Self
15    where
16        // 4. add a `Self: Tabulate` bound to constructors
17        Self: Tabulate,
18    {
19        Self {
20            v,
21            // 5. and initialize your `Instance` field like so:
22            _instance: Instance::new(),
23        }
24    }
25
26    pub fn v(self) -> T {
27        self.v
28    }
29}
30
31fn main() {
32    // you can now query the number of extant instances of `Foo`!
33    assert_eq!(Foo::<i8>::instances(), 0);
34    assert_eq!(Foo::<u8>::instances(), 0);
35
36    // the same counter is shared for all generic instantiations
37    let mut bar: Vec<Foo<i8>> = vec![Foo::new(0i8); 10];
38
39    assert_eq!(Foo::<i8>::instances(), 10);
40    assert_eq!(Foo::<u8>::instances(), 10);
41
42    let _baz: Vec<Foo<u8>> = vec![Foo::new(0u8); 5];
43
44    assert_eq!(Foo::<i8>::instances(), 15);
45    assert_eq!(Foo::<u8>::instances(), 15);
46
47    let _ = bar.drain(0..5);
48
49    assert_eq!(Foo::<i8>::instances(), 10);
50    assert_eq!(Foo::<u8>::instances(), 10);
51}