euv-core 0.52.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use super::*;

/// Human-readable formatting for `DispatchError`.
impl fmt::Display for DispatchError {
    /// Formats a `DispatchError` diagnostic message.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting status.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        let message: &str = match self {
            Self::QueueFull => DISPATCHER_ERR_QUEUE_FULL,
            Self::Closed => DISPATCHER_ERR_CLOSED,
            Self::LockPoisoned => DISPATCHER_ERR_LOCK_POISONED,
        };
        formatter.write_str(message)
    }
}

/// Standard `Error` implementation for `DispatchError`.
impl Error for DispatchError {}

/// Safe optional wakeup hook getter for `UiDispatcherQueues`.
impl UiDispatcherQueues {
    /// Clones the installed event-loop wakeup callback without panicking when absent.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<dyn Fn() + Send + Sync>>` - Cloned wakeup callback handle, if registered.
    #[must_use]
    pub(crate) fn try_get_wakeup_hook(&self) -> Option<Arc<dyn Fn() + Send + Sync>> {
        self.wakeup_hook.clone()
    }
}

/// Structured diagnostic `Debug` formatting for `UiDispatcher`.
impl fmt::Debug for UiDispatcher {
    /// Formats live atomic dispatcher metrics without locking the internal queue.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting status.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        let snapshot: UiDispatchMetrics = self.metrics();
        write!(
            formatter,
            "UiDispatcher(pending={}, capacity={}, peak={}, enqueued={}, drained={}, closed={})",
            snapshot.get_pending_count(),
            snapshot.get_capacity(),
            snapshot.get_peak_depth(),
            snapshot.get_enqueued_total(),
            snapshot.get_drained_total(),
            snapshot.get_closed(),
        )
    }
}

/// Default bounded `UiDispatcher` using `DEFAULT_DISPATCHER_CAPACITY` and `RejectNew` backpressure.
impl Default for UiDispatcher {
    /// Creates a default bounded `UiDispatcher`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready cross-thread UI dispatcher handle.
    fn default() -> Self {
        Self::with_capacity(
            DEFAULT_DISPATCHER_CAPACITY,
            DispatchBackpressurePolicy::RejectNew,
        )
    }
}

/// Cross-thread posting, wakeup coalescing, and bounded UI-thread draining for `UiDispatcher`.
impl UiDispatcher {
    /// Creates a new `UiDispatcher` with an explicit queue capacity and backpressure policy.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of buffered pending tasks (clamped to `>= 1`).
    /// - `DispatchBackpressurePolicy` - Policy applied when the queue reaches capacity.
    ///
    /// # Returns
    ///
    /// - `Self` - Thread-safe `UiDispatcher` handle.
    #[must_use]
    pub fn with_capacity(capacity: usize, policy: DispatchBackpressurePolicy) -> Self {
        let bounded_capacity: usize = capacity.max(1);
        let shared: UiDispatcherShared = UiDispatcherShared {
            capacity: bounded_capacity,
            policy,
            queues: Mutex::new(UiDispatcherQueues::default()),
            pending_count: AtomicUsize::new(0),
            peak_depth: AtomicUsize::new(0),
            enqueued_total: AtomicU64::new(0),
            drained_total: AtomicU64::new(0),
            rejected_total: AtomicU64::new(0),
            dropped_total: AtomicU64::new(0),
            wakeup_invocations: AtomicU64::new(0),
            wakeup_pending: AtomicBool::new(false),
            closed: AtomicBool::new(false),
        };
        Self {
            shared: Arc::new(shared),
        }
    }

    /// Registers a platform event-loop wakeup callback invoked once whenever the queue transitions from idle to pending.
    ///
    /// # Arguments
    ///
    /// - `WakeFn` - Thread-safe wakeup callback (for example, signaling a `CFRunLoopSource`, Win32 event, or eventfd).
    pub fn set_wakeup_hook<WakeFn>(&self, hook: WakeFn)
    where
        WakeFn: Fn() + Send + Sync + 'static,
    {
        if let Ok(mut guard) = self.get_shared().get_queues().lock() {
            guard.set_wakeup_hook(Some(Arc::new(hook)));
        }
    }

    /// Removes any previously installed event-loop wakeup callback.
    pub fn clear_wakeup_hook(&self) {
        if let Ok(mut guard) = self.get_shared().get_queues().lock() {
            guard.set_wakeup_hook(None);
        }
    }

    /// Enqueues a normal-priority UI mutation closure from any thread and signals the wakeup hook if coalescing permits.
    ///
    /// # Arguments
    ///
    /// - `TaskFn` - Sendable closure to execute on the UI thread.
    ///
    /// # Returns
    ///
    /// - `Result<u64, DispatchError>` - Monotonic submission sequence number or backpressure/closure error.
    pub fn dispatch<TaskFn>(&self, task: TaskFn) -> Result<u64, DispatchError>
    where
        TaskFn: FnOnce() + Send + 'static,
    {
        self.dispatch_with_priority(DispatchPriority::Normal, task)
    }

    /// Enqueues a UI mutation closure into the specified priority lane and signals the wakeup hook if needed.
    ///
    /// # Arguments
    ///
    /// - `DispatchPriority` - Priority lane (`Critical`, `Normal`, or `Background`).
    /// - `TaskFn` - Sendable closure to execute on the UI thread.
    ///
    /// # Returns
    ///
    /// - `Result<u64, DispatchError>` - Monotonic submission sequence number or backpressure/closure error.
    pub fn dispatch_with_priority<TaskFn>(
        &self,
        priority: DispatchPriority,
        task: TaskFn,
    ) -> Result<u64, DispatchError>
    where
        TaskFn: FnOnce() + Send + 'static,
    {
        let shared: &UiDispatcherShared = self.get_shared().as_ref();
        if shared.get_closed().load(Ordering::Acquire) {
            let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
            return Err(DispatchError::Closed);
        }
        let wakeup_to_call: Option<Arc<dyn Fn() + Send + Sync>>;
        let assigned_sequence: u64;
        {
            let Ok(mut guard) = shared.get_queues().lock() else {
                let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
                return Err(DispatchError::LockPoisoned);
            };
            if shared.get_closed().load(Ordering::Acquire) {
                let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
                return Err(DispatchError::Closed);
            }
            let current_len: usize = total_queued_tasks(&guard);
            if current_len >= shared.get_capacity() {
                match shared.get_policy() {
                    DispatchBackpressurePolicy::RejectNew => {
                        let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
                        return Err(DispatchError::QueueFull);
                    }
                    DispatchBackpressurePolicy::DropOldest => {
                        if drop_oldest_lowest_priority_task(&mut guard) {
                            let _: u64 = shared.get_dropped_total().fetch_add(1, Ordering::Relaxed);
                        }
                    }
                }
            }
            let next_seq: u64 = guard.get_next_sequence().saturating_add(1);
            guard.set_next_sequence(next_seq);
            assigned_sequence = next_seq;
            let envelope: UiDispatchTask = UiDispatchTask {
                sequence: assigned_sequence,
                priority,
                callback: Box::new(task),
            };
            match priority {
                DispatchPriority::Critical => guard.get_mut_critical().push_back(envelope),
                DispatchPriority::Normal => guard.get_mut_normal().push_back(envelope),
                DispatchPriority::Background => guard.get_mut_background().push_back(envelope),
            }
            let updated_len: usize = total_queued_tasks(&guard);
            shared
                .get_pending_count()
                .store(updated_len, Ordering::Release);
            update_atomic_peak(shared.get_peak_depth(), updated_len);
            let _: u64 = shared.get_enqueued_total().fetch_add(1, Ordering::Relaxed);
            let should_wake: bool = !shared.get_wakeup_pending().swap(true, Ordering::AcqRel);
            wakeup_to_call = if should_wake {
                guard.try_get_wakeup_hook()
            } else {
                None
            };
        }
        if let Some(wakeup_fn) = wakeup_to_call {
            let _: u64 = shared
                .get_wakeup_invocations()
                .fetch_add(1, Ordering::Relaxed);
            wakeup_fn();
        }
        Ok(assigned_sequence)
    }

    /// Returns `true` when at least one queued task awaits UI-thread draining (lock-free atomic read).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if pending tasks exist.
    #[must_use]
    pub fn has_pending(&self) -> bool {
        self.pending_len() > 0
    }

    /// Returns the approximate count of pending queued tasks via a lock-free atomic load.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of buffered tasks awaiting execution.
    #[must_use]
    pub fn pending_len(&self) -> usize {
        self.get_shared()
            .get_pending_count()
            .load(Ordering::Acquire)
    }

    /// Pops up to `max_tasks` prioritized tasks from the internal queues and updates pending counters.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of tasks to pop in one batch.
    ///
    /// # Returns
    ///
    /// - `(Vec<UiDispatchTask>, usize)` - Popped batch paired with the number of remaining queued tasks.
    fn pop_batch(&self, max_tasks: usize) -> (Vec<UiDispatchTask>, usize) {
        let shared: &UiDispatcherShared = self.get_shared().as_ref();
        if max_tasks == 0 || !self.has_pending() {
            return (Vec::new(), self.pending_len());
        }
        let Ok(mut guard) = shared.get_queues().lock() else {
            return (Vec::new(), self.pending_len());
        };
        let available: usize = total_queued_tasks(&guard);
        let take_count: usize = available.min(max_tasks);
        let mut drained: Vec<UiDispatchTask> = Vec::with_capacity(take_count);
        for _ in 0..take_count {
            if let Some(task) = pop_next_prioritized_task(&mut guard) {
                drained.push(task);
            }
        }
        let remaining: usize = total_queued_tasks(&guard);
        shared
            .get_pending_count()
            .store(remaining, Ordering::Release);
        if remaining == 0 {
            shared.get_wakeup_pending().store(false, Ordering::Release);
        }
        (drained, remaining)
    }

    /// Drains and executes up to `max_tasks` queued tasks on the UI thread inside a coalesced reactive `batch`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of tasks to execute in this frame slice.
    ///
    /// # Returns
    ///
    /// - `UiDrainSummary` - Executed count and remaining pending count.
    pub fn drain_budget(&self, max_tasks: usize) -> UiDrainSummary {
        let (tasks, remaining): (Vec<UiDispatchTask>, usize) = self.pop_batch(max_tasks);
        let executed: usize = tasks.len();
        if executed == 0 {
            return UiDrainSummary::new(0, remaining, 0);
        }
        batch(|| {
            for task in tasks {
                let UiDispatchTask {
                    sequence: _sequence,
                    priority: _priority,
                    callback,
                } = task;
                callback();
            }
        });
        let _: u64 = self
            .get_shared()
            .get_drained_total()
            .fetch_add(executed as u64, Ordering::Relaxed);
        let live_remaining: usize = self.pending_len();
        UiDrainSummary::new(executed, live_remaining, 0)
    }

    /// Drains up to `max_tasks` queued tasks inside a reactive `batch`, isolating each task panic with `boundary`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of tasks to execute in this frame slice.
    /// - `&mut ErrorBoundary` - Fault boundary capturing panics from individual queued closures.
    /// - `u64` - Monotonic timestamp in milliseconds stamped on any captured fault record.
    ///
    /// # Returns
    ///
    /// - `UiDrainSummary` - Executed count, remaining pending count, and number of panics isolated.
    pub fn drain_budget_isolated(
        &self,
        max_tasks: usize,
        boundary: &mut ErrorBoundary,
        timestamp_ms: u64,
    ) -> UiDrainSummary {
        let (tasks, remaining): (Vec<UiDispatchTask>, usize) = self.pop_batch(max_tasks);
        let executed: usize = tasks.len();
        if executed == 0 {
            return UiDrainSummary::new(0, remaining, 0);
        }
        let mut panics_caught: usize = 0;
        batch(|| {
            for task in tasks {
                let UiDispatchTask {
                    sequence: _sequence,
                    priority: _priority,
                    callback,
                } = task;
                let outcome: Result<(), FaultRecord> = boundary.guard(
                    FaultOrigin::DispatcherTask,
                    DISPATCHER_FAULT_SCOPE,
                    timestamp_ms,
                    callback,
                );
                if outcome.is_err() {
                    panics_caught = panics_caught.saturating_add(1);
                }
            }
        });
        let _: u64 = self
            .get_shared()
            .get_drained_total()
            .fetch_add(executed as u64, Ordering::Relaxed);
        let live_remaining: usize = self.pending_len();
        UiDrainSummary::new(executed, live_remaining, panics_caught)
    }

    /// Drains all currently queued tasks on the UI thread in bounded slices until the queue is empty.
    ///
    /// # Returns
    ///
    /// - `UiDrainSummary` - Aggregate executed task count and remaining pending count.
    pub fn drain_all(&self) -> UiDrainSummary {
        let mut total_executed: usize = 0;
        loop {
            let pending: usize = self.pending_len();
            if pending == 0 {
                break;
            }
            let slice: UiDrainSummary =
                self.drain_budget(pending.max(DEFAULT_DISPATCHER_BATCH_LIMIT));
            total_executed = total_executed.saturating_add(slice.get_executed());
            if slice.get_executed() == 0 {
                break;
            }
        }
        UiDrainSummary::new(total_executed, self.pending_len(), 0)
    }

    /// Marks the dispatcher closed so subsequent cross-thread `dispatch` calls fail with `DispatchError::Closed`.
    pub fn close(&self) {
        self.get_shared()
            .get_closed()
            .store(true, Ordering::Release);
    }

    /// Returns `true` once `close()` has been called on this dispatcher.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when closed to new submissions.
    #[must_use]
    pub fn is_closed(&self) -> bool {
        self.get_shared().get_closed().load(Ordering::Acquire)
    }

    /// Captures a lock-free telemetry snapshot of queue occupancy, peak depth, and backpressure counts.
    ///
    /// # Returns
    ///
    /// - `UiDispatchMetrics` - Current wait-free dispatcher metrics.
    #[must_use]
    pub fn metrics(&self) -> UiDispatchMetrics {
        let shared: &UiDispatcherShared = self.get_shared().as_ref();
        UiDispatchMetrics {
            pending_count: shared.get_pending_count().load(Ordering::Acquire),
            capacity: shared.get_capacity(),
            peak_depth: shared.get_peak_depth().load(Ordering::Acquire),
            enqueued_total: shared.get_enqueued_total().load(Ordering::Relaxed),
            drained_total: shared.get_drained_total().load(Ordering::Relaxed),
            rejected_total: shared.get_rejected_total().load(Ordering::Relaxed),
            dropped_total: shared.get_dropped_total().load(Ordering::Relaxed),
            wakeup_invocations: shared.get_wakeup_invocations().load(Ordering::Relaxed),
            closed: shared.get_closed().load(Ordering::Acquire),
        }
    }
}