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
use std::{
    cell::RefCell,
    marker::PhantomData,
    mem::take,
    sync::{Condvar, Mutex},
};

use crate::Record;

thread_local! {
    static ACTUAL_LOCAL: RefCell<Option<Vec<Record>>> = RefCell::new(None);
}

static ACTUAL_GLOBAL: Mutex<Option<Vec<Record>>> = Mutex::new(None);
static ACTUAL_GLOBAL_CONDVAR: Condvar = Condvar::new();

pub trait Thread {
    fn init() -> Self;
    fn take_actual(&self) -> Records;
}

pub struct Local(PhantomData<*mut ()>);

impl Thread for Local {
    fn init() -> Self {
        ACTUAL_LOCAL.with(|actual| {
            let mut actual = actual.borrow_mut();
            if actual.is_some() {
                panic!("CallRecorder::new_local() is already called in this thread");
            }
            *actual = Some(Vec::new());
        });
        Self(PhantomData)
    }
    fn take_actual(&self) -> Records {
        Records(ACTUAL_LOCAL.with(|actual| take(actual.borrow_mut().as_mut().unwrap())))
    }
}
impl Drop for Local {
    fn drop(&mut self) {
        ACTUAL_LOCAL.with(|actual| actual.borrow_mut().take());
    }
}

#[non_exhaustive]
pub struct Global {}

impl Thread for Global {
    fn init() -> Self {
        let mut actual = ACTUAL_GLOBAL.lock().unwrap();
        while actual.is_some() {
            actual = ACTUAL_GLOBAL_CONDVAR.wait(actual).unwrap();
        }
        *actual = Some(Vec::new());
        Self {}
    }
    fn take_actual(&self) -> Records {
        Records(take(ACTUAL_GLOBAL.lock().unwrap().as_mut().unwrap()))
    }
}
impl Drop for Global {
    fn drop(&mut self) {
        ACTUAL_GLOBAL.lock().unwrap().take();
        ACTUAL_GLOBAL_CONDVAR.notify_all();
    }
}

pub struct Records(pub(crate) Vec<Record>);

impl Records {
    #[track_caller]
    pub fn push(id: String, file: &'static str, line: u32) {
        ACTUAL_LOCAL.with(|actual| {
            let r = Record { id, file, line };
            if let Some(actual) = &mut *actual.borrow_mut() {
                actual.push(r);
            } else if let Some(seq) = ACTUAL_GLOBAL.lock().unwrap().as_mut() {
                seq.push(r);
            }
        });
    }
}