fidget_core/render/config.rs
1//! Types used in configuration structures
2use std::sync::{
3 Arc,
4 atomic::{AtomicBool, Ordering},
5};
6
7/// Thread pool to use for multithreaded rendering
8///
9/// Most users will use the global Rayon pool, but it's possible to provide your
10/// own as well.
11pub enum ThreadPool {
12 /// User-provided pool
13 Custom(rayon::ThreadPool),
14 /// Global Rayon pool
15 Global,
16}
17
18impl ThreadPool {
19 /// Runs a function across the thread pool
20 pub fn run<F: FnOnce() -> V + Send, V: Send>(&self, f: F) -> V {
21 match self {
22 ThreadPool::Custom(p) => p.install(f),
23 ThreadPool::Global => f(),
24 }
25 }
26
27 /// Returns the number of threads in the pool
28 pub fn thread_count(&self) -> usize {
29 match self {
30 ThreadPool::Custom(p) => p.current_num_threads(),
31 ThreadPool::Global => rayon::current_num_threads(),
32 }
33 }
34}
35
36/// Token to cancel an in-progress operation
37#[derive(Clone, Default)]
38pub struct CancelToken(Arc<AtomicBool>);
39
40impl CancelToken {
41 /// Build a new token, which is initialize as "not cancelled"
42 pub fn new() -> Self {
43 Self::default()
44 }
45
46 /// Mark this token as cancelled
47 pub fn cancel(&self) {
48 self.0.store(true, Ordering::Relaxed);
49 }
50
51 /// Check if the token is cancelled
52 pub fn is_cancelled(&self) -> bool {
53 self.0.load(Ordering::Relaxed)
54 }
55
56 /// Returns a raw pointer to the inner flag
57 ///
58 /// This is used in shared memory environments where the `CancelToken`
59 /// itself cannot be passed between threads, i.e. to send a cancel token to
60 /// a web worker.
61 ///
62 /// To avoid a memory leak, the pointer must be converted back to a
63 /// `CancelToken` using [`CancelToken::from_raw`]. In the meantime, users
64 /// should refrain from writing to the raw pointer.
65 #[doc(hidden)]
66 pub fn into_raw(self) -> *const AtomicBool {
67 Arc::into_raw(self.0)
68 }
69
70 /// Reclaims a released cancel token pointer
71 ///
72 /// # Safety
73 /// The pointer must have been previously returned by a call to
74 /// [`CancelToken::into_raw`].
75 #[doc(hidden)]
76 pub unsafe fn from_raw(ptr: *const AtomicBool) -> Self {
77 let a = unsafe { Arc::from_raw(ptr) };
78 Self(a)
79 }
80}