summaryrefslogtreecommitdiffstats
path: root/vendor/countme/src/imp.rs
blob: c1ace0da72c7a005d6038531ebc2f390d4ce4fb6 (plain)
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
use std::{
    any::{type_name, TypeId},
    cell::RefCell,
    collections::HashMap,
    hash::BuildHasherDefault,
    os::raw::c_int,
    sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed},
    sync::Arc,
};

use dashmap::DashMap;
use once_cell::sync::OnceCell;
use rustc_hash::FxHasher;

use crate::{AllCounts, Counts};

static ENABLE: AtomicBool = AtomicBool::new(cfg!(feature = "print_at_exit"));

type GlobalStore = DashMap<TypeId, Arc<Store>, BuildHasherDefault<FxHasher>>;

#[inline]
fn global_store() -> &'static GlobalStore {
    static MAP: OnceCell<GlobalStore> = OnceCell::new();
    MAP.get_or_init(|| {
        if cfg!(feature = "print_at_exit") {
            extern "C" {
                fn atexit(f: extern "C" fn()) -> c_int;
            }
            extern "C" fn print_at_exit() {
                eprint!("{}", get_all());
            }
            unsafe {
                atexit(print_at_exit);
            }
        }

        GlobalStore::default()
    })
}

thread_local! {
    static LOCAL: RefCell<HashMap<TypeId, Arc<Store>, BuildHasherDefault<FxHasher>>> = RefCell::default();
}

pub(crate) fn enable(yes: bool) {
    ENABLE.store(yes, Relaxed);
}

#[inline]
fn enabled() -> bool {
    ENABLE.load(Relaxed)
}

#[inline]
pub(crate) fn dec<T: 'static>() {
    if enabled() {
        do_dec(TypeId::of::<T>())
    }
}
#[inline(never)]
fn do_dec(key: TypeId) {
    LOCAL.with(|local| {
        // Fast path: we have needed store in thread local map
        if let Some(store) = local.borrow().get(&key) {
            store.dec();
            return;
        }

        let global = global_store();

        // Slightly slower: we don't have needed store in our thread local map,
        // but some other thread has already initialized the needed store in the global map
        if let Some(store) = global.get(&key) {
            let store = store.value();
            local.borrow_mut().insert(key, Arc::clone(store));
            store.inc();
            return;
        }

        // We only decrement counter after incremenrting it, so this line is unreachable
    })
}

#[inline]
pub(crate) fn inc<T: 'static>() {
    if enabled() {
        do_inc(TypeId::of::<T>(), type_name::<T>())
    }
}
#[inline(never)]
fn do_inc(key: TypeId, name: &'static str) {
    LOCAL.with(|local| {
        // Fast path: we have needed store in thread local map
        if let Some(store) = local.borrow().get(&key) {
            store.inc();
            return;
        }

        let global = global_store();

        let copy = match global.get(&key) {
            // Slightly slower path: we don't have needed store in our thread local map,
            // but some other thread has already initialized the needed store in the global map
            Some(store) => {
                let store = store.value();
                store.inc();
                Arc::clone(store)
            }
            // Slow path: we are the first to initialize both global and local maps
            None => {
                let store = global
                    .entry(key)
                    .or_insert_with(|| Arc::new(Store { name, ..Store::default() }))
                    .downgrade();
                let store = store.value();

                store.inc();
                Arc::clone(store)
            }
        };

        local.borrow_mut().insert(key, copy);
    });
}

pub(crate) fn get<T: 'static>() -> Counts {
    do_get(TypeId::of::<T>())
}
fn do_get(key: TypeId) -> Counts {
    global_store().entry(key).or_default().value().read()
}

pub(crate) fn get_all() -> AllCounts {
    let mut entries = global_store()
        .iter()
        .map(|entry| {
            let store = entry.value();
            (store.type_name(), store.read())
        })
        .collect::<Vec<_>>();
    entries.sort_by_key(|(name, _counts)| *name);
    AllCounts { entries }
}

#[derive(Default)]
struct Store {
    total: AtomicUsize,
    max_live: AtomicUsize,
    live: AtomicUsize,
    name: &'static str,
}

impl Store {
    fn inc(&self) {
        self.total.fetch_add(1, Relaxed);
        let live = self.live.fetch_add(1, Relaxed) + 1;
        self.max_live.fetch_max(live, Relaxed);
    }

    fn dec(&self) {
        self.live.fetch_sub(1, Relaxed);
    }

    fn read(&self) -> Counts {
        Counts {
            total: self.total.load(Relaxed),
            max_live: self.max_live.load(Relaxed),
            live: self.live.load(Relaxed),
        }
    }

    fn type_name(&self) -> &'static str {
        self.name
    }
}