Skip to main content

luaur_common/methods/
thread_context_flush_events.rs

1//! Source: `Common/include/Luau/TimeTrace.h:82-93` (hand-ported)
2//! C++ `ThreadContext::flushEvents()`.
3use crate::enums::event_type::EventType;
4use crate::functions::create_token::create_token;
5use crate::functions::flush_events::flush_events;
6use crate::functions::get_clock_microseconds::get_clock_microseconds;
7use crate::records::event::Event;
8use crate::records::event::EventData;
9use crate::records::thread_context::ThreadContext;
10use core::sync::atomic::{AtomicU16, Ordering};
11
12impl ThreadContext {
13    pub fn flush_events(&mut self) {
14        // `static uint16_t flushToken = createToken(*globalContext, "flushEvents", "TimeTrace");`
15        static FLUSH_TOKEN: AtomicU16 = AtomicU16::new(0);
16        static INITIALIZED: core::sync::atomic::AtomicBool =
17            core::sync::atomic::AtomicBool::new(false);
18
19        // `GlobalContext` guards its mutable state behind a Mutex, so the shared
20        // Arc handle is enough for both `createToken` and `flushEvents`.
21        let global_context = self.global_context.clone();
22
23        if !INITIALIZED.load(Ordering::Relaxed) {
24            let token = create_token(
25                &global_context,
26                c"flushEvents".as_ptr(),
27                c"TimeTrace".as_ptr(),
28            );
29            FLUSH_TOKEN.store(token, Ordering::Relaxed);
30            INITIALIZED.store(true, Ordering::Relaxed);
31        }
32
33        let flush_token = FLUSH_TOKEN.load(Ordering::Relaxed);
34
35        // events.push_back({EventType::Enter, flushToken, {getClockMicroseconds()}});
36        self.events.push(Event {
37            r#type: EventType::Enter,
38            token: flush_token,
39            data: EventData {
40                microsec: get_clock_microseconds(),
41            },
42        });
43
44        // TimeTrace::flushEvents(*globalContext, threadId, events, data);
45        flush_events(&global_context, self.thread_id, &self.events, &self.data);
46
47        // events.clear(); data.clear();
48        self.events.clear();
49        self.data.clear();
50
51        // events.push_back({EventType::Leave, 0, {getClockMicroseconds()}});
52        self.events.push(Event {
53            r#type: EventType::Leave,
54            token: 0,
55            data: EventData {
56                microsec: get_clock_microseconds(),
57            },
58        });
59    }
60}