Skip to main content

swift_runtime/
concurrency.rs

1//! Safe concurrency runtime accessors.
2//!
3//! Wraps the Swift concurrency runtime (tasks, executors, time).
4//! Only exposes the current (non-deprecated) APIs from Swift 6.3.
5
6use core::ffi::c_void;
7
8/// An executor reference (identity + implementation pair).
9#[derive(Debug, Clone, Copy)]
10pub struct Executor {
11    pub identity: *const c_void,
12    pub implementation: *const c_void,
13}
14
15/// Get the main executor.
16pub fn main_executor() -> Option<Executor> {
17    let result = unsafe { swift_runtime_sys::ConcurrencyThunks::swift_task_getMainExecutor() };
18    result.ok().map(|e| Executor {
19        identity: e.identity,
20        implementation: e.implementation,
21    })
22}
23
24/// Get the current executor (if running inside a task).
25pub fn current_executor() -> Option<Executor> {
26    let result = unsafe { swift_runtime_sys::ConcurrencyThunks::swift_task_getCurrentExecutor() };
27    result.ok().map(|e| Executor {
28        identity: e.identity,
29        implementation: e.implementation,
30    })
31}
32
33/// Check whether an executor is the main executor.
34pub fn is_main_executor(executor: &Executor) -> Option<bool> {
35    let raw = swift_runtime_sys::ConcurrencyThunks::SerialExecutorRef {
36        identity: executor.identity,
37        implementation: executor.implementation,
38    };
39    unsafe { swift_runtime_sys::ConcurrencyThunks::swift_task_isMainExecutor(raw) }.ok()
40}
41
42/// A monotonic time reading from the Swift concurrency clock.
43#[derive(Debug, Clone, Copy)]
44pub struct SwiftTime {
45    pub seconds: i64,
46    pub nanoseconds: i64,
47}
48
49/// Read the continuous (monotonic) clock used by Swift concurrency.
50pub fn continuous_time() -> Option<SwiftTime> {
51    let mut sec: i64 = 0;
52    let mut nsec: i64 = 0;
53    let result =
54        unsafe { swift_runtime_sys::ConcurrencyThunks::swift_get_time(&mut sec, &mut nsec, 1) };
55    result.ok().map(|_| SwiftTime {
56        seconds: sec,
57        nanoseconds: nsec,
58    })
59}
60
61/// Read the suspending clock used by Swift concurrency.
62pub fn suspending_time() -> Option<SwiftTime> {
63    let mut sec: i64 = 0;
64    let mut nsec: i64 = 0;
65    // clock 1 = continuous, clock 2 = suspending
66    let result =
67        unsafe { swift_runtime_sys::ConcurrencyThunks::swift_get_time(&mut sec, &mut nsec, 2) };
68    result.ok().map(|_| SwiftTime {
69        seconds: sec,
70        nanoseconds: nsec,
71    })
72}