derive_distributedcounter/
derive-distributedcounter.rs

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