euv-core 0.48.0

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use super::*;

/// Constructor helpers for `PrewarmContextKey`.
impl PrewarmContextKey {
    /// Computes a deterministic 64-bit FNV-1a digest over a BCP-47 locale string (`0` for empty).
    ///
    /// # Arguments
    ///
    /// - `&str` - BCP-47 locale tag.
    ///
    /// # Returns
    ///
    /// - `u64` - Locale hash digest (`0` when `locale` is empty).
    #[must_use]
    pub fn hash_locale(locale: &str) -> u64 {
        if locale.is_empty() {
            return 0;
        }
        let mut h: u64 = FNV1A_OFFSET_BASIS;
        for &b in locale.as_bytes().iter() {
            h ^= b as u64;
            h = h.wrapping_mul(FNV1A_PRIME);
        }
        if h == 0 { 1 } else { h }
    }

    /// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, and display `dpr`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Application or bundle resource version.
    /// - `ThemeMode` - Active light or dark theme mode.
    /// - `f32` - Active display scale factor.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized context key.
    #[must_use]
    pub fn from_context(resource_version: u64, theme_mode: ThemeMode, dpr: f32) -> Self {
        Self {
            resource_version,
            theme_mode,
            dpr_bits: dpr.max(0.5).to_bits(),
            locale_hash: 0,
        }
    }

    /// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, `dpr`, and `locale`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Application or bundle resource version.
    /// - `ThemeMode` - Active light or dark theme mode.
    /// - `f32` - Active display scale factor.
    /// - `&str` - Active BCP-47 locale tag.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized full context key.
    #[must_use]
    pub fn from_full_context(
        resource_version: u64,
        theme_mode: ThemeMode,
        dpr: f32,
        locale: &str,
    ) -> Self {
        Self {
            resource_version,
            theme_mode,
            dpr_bits: dpr.max(0.5).to_bits(),
            locale_hash: Self::hash_locale(locale),
        }
    }

    /// Returns a copy of this context key updated with the hashed `locale` tag.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base context key.
    /// - `&str` - Active BCP-47 locale tag.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated context key bound to `locale`.
    #[must_use]
    pub fn with_locale(mut self, locale: &str) -> Self {
        self.set_locale_hash(Self::hash_locale(locale));
        self
    }
}

/// Builder helpers for `RoutePrewarmTask`.
impl RoutePrewarmTask {
    /// Creates a new bounded route pre-warm task descriptor.
    ///
    /// # Arguments
    ///
    /// - `String` - Target route key.
    /// - `PrewarmWorkKind` - Pre-warm phase kind.
    /// - `PrewarmContextKey` - Active context signature `(version, theme, DPR, locale)`.
    /// - `usize` - Estimated memory/upload footprint in bytes.
    /// - `u64` - Estimated execution cost in microseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready pre-warm task descriptor with default priority `1`.
    #[must_use]
    pub fn new(
        route_key: String,
        kind: PrewarmWorkKind,
        context: PrewarmContextKey,
        estimated_bytes: usize,
        estimated_us: u64,
    ) -> Self {
        Self {
            route_key,
            kind,
            context,
            estimated_bytes,
            estimated_us: estimated_us.max(1),
            priority: 1,
            sample_text: String::new(),
        }
    }

    /// Sets task execution priority (`0` = highest).
    ///
    /// # Arguments
    ///
    /// - `Self` - Base task descriptor.
    /// - `u8` - Priority level (`0` executes first).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated task descriptor.
    #[must_use]
    pub fn with_priority(mut self, priority: u8) -> Self {
        self.set_priority(priority);
        self
    }

    /// Attaches representative route text so idle `TextShaping`/`GlyphRaster` slices warm the shared shaping cache.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base task descriptor.
    /// - `String` - Sample route heading or copy to warm.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated task descriptor.
    #[must_use]
    pub fn with_sample_text(mut self, sample_text: String) -> Self {
        self.set_sample_text(sample_text);
        self
    }
}

/// Default bounded `RoutePrewarmer` initialized with conservative memory and per-frame slice caps.
impl Default for RoutePrewarmer {
    /// Creates a default `RoutePrewarmer` with 32 max tasks, 8 MiB memory cap, and 1 MiB/frame upload cap.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready route pre-warmer.
    fn default() -> Self {
        Self::with_limits(
            PREWARM_DEFAULT_MAX_TASKS,
            PREWARM_DEFAULT_MAX_MEMORY_BYTES,
            PREWARM_DEFAULT_MAX_UPLOAD_PER_FRAME,
        )
    }
}

/// Bounded queueing, budgeted slicing, context invalidation, and cancellation for `RoutePrewarmer`.
impl RoutePrewarmer {
    /// Creates a `RoutePrewarmer` with explicit queue, memory, and per-frame upload byte caps.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum pending tasks (`>= 1`).
    /// - `usize` - Maximum aggregate artifact memory in bytes (`>= 4096`).
    /// - `usize` - Maximum bytes uploaded/processed per budgeted frame step (`>= 4096`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured route pre-warmer.
    #[must_use]
    pub fn with_limits(
        max_pending_tasks: usize,
        max_memory_bytes: usize,
        max_upload_bytes_per_frame: usize,
    ) -> Self {
        Self {
            max_pending_tasks: max_pending_tasks.max(1),
            max_memory_bytes: max_memory_bytes.max(4096),
            max_upload_bytes_per_frame: max_upload_bytes_per_frame.max(4096),
            default_step_budget_us: PREWARM_DEFAULT_STEP_BUDGET_US,
            active_context: PrewarmContextKey::from_context(1, ThemeMode::Light, 1.0),
            enabled: true,
            pending: Vec::new(),
            ready: Vec::new(),
            resident_bytes: 0,
            enqueued_count: 0,
            executed_tasks: 0,
            cancelled_tasks: 0,
            invalidated_artifacts: 0,
            budget_deferrals: 0,
            preempted_until_idle: false,
            idle_slices_executed: 0,
        }
    }

    /// Preempts speculative route pre-warming immediately when user input or navigation begins.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    pub fn preempt(&mut self) {
        let Self {
            preempted_until_idle,
            ..
        } = self;
        *preempted_until_idle = true;
    }

    /// Executes real time-sliced post-Frame-1 idle pre-warming strictly within `<= 500 us` and yields immediately on input or navigation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR, locale)` context.
    /// - `u64` - Foreground frame CPU duration already spent in microseconds.
    /// - `bool` - True when user input, scrolling, or navigation occurred on this frame.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of pre-warm tasks completed during this idle slice.
    pub fn step_idle_post_frame1(
        &mut self,
        active_context: PrewarmContextKey,
        frame_work_us: u64,
        had_input_or_nav: bool,
    ) -> usize {
        if had_input_or_nav {
            self.preempt();
            return 0;
        }
        if !self.get_enabled() || self.get_pending().is_empty() {
            let Self {
                preempted_until_idle,
                ..
            } = self;
            *preempted_until_idle = false;
            return 0;
        }
        if self.get_preempted_until_idle() {
            let Self {
                preempted_until_idle,
                ..
            } = self;
            *preempted_until_idle = false;
            return 0;
        }
        let max_slice_us: u64 = self
            .get_default_step_budget_us()
            .min(PREWARM_DEFAULT_STEP_BUDGET_US);
        let remaining_us: u64 = max_slice_us.saturating_sub(frame_work_us);
        if remaining_us == 0 {
            return 0;
        }
        let done: usize = self.step_budgeted(active_context, remaining_us);
        if done > 0 {
            let Self {
                idle_slices_executed,
                ..
            } = self;
            *idle_slices_executed = idle_slices_executed.saturating_add(1);
        }
        done
    }

    /// Enqueues `task` if pre-warming is enabled, context matches, queue has capacity, and no duplicate `(route, kind)` exists.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `RoutePrewarmTask` - Candidate pre-warm task.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if accepted into the bounded queue.
    pub fn enqueue(&mut self, task: RoutePrewarmTask) -> bool {
        if !self.get_enabled() {
            return false;
        }
        if task.get_context() != self.get_active_context() {
            let Self {
                cancelled_tasks, ..
            } = self;
            *cancelled_tasks = cancelled_tasks.saturating_add(1);
            return false;
        }
        if self.get_pending().len() >= self.get_max_pending_tasks() {
            return false;
        }
        let duplicate: bool = self
            .get_pending()
            .iter()
            .any(|existing: &RoutePrewarmTask| {
                existing.get_route_key() == task.get_route_key()
                    && existing.get_kind() == task.get_kind()
            });
        if duplicate {
            return false;
        }
        let Self {
            pending,
            enqueued_count,
            ..
        } = self;
        pending.push(task);
        pending.sort_by_key(|t: &RoutePrewarmTask| t.get_priority());
        *enqueued_count = enqueued_count.saturating_add(1);
        true
    }

    /// Invalidates all pending tasks and ready artifacts when `(resource_version, theme_mode, dpr)` changes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `PrewarmContextKey` - Newly active `(version, theme, DPR)` context key.
    ///
    /// # Returns
    ///
    /// - `usize` - Total stale pending tasks plus invalidated ready artifacts discarded.
    pub fn invalidate_context(&mut self, next_context: PrewarmContextKey) -> usize {
        if self.get_active_context() == next_context {
            return 0;
        }
        let Self {
            active_context,
            pending,
            ready,
            resident_bytes,
            cancelled_tasks,
            invalidated_artifacts,
            ..
        } = self;
        *active_context = next_context;
        let dropped_pending: usize = pending.len();
        let dropped_ready: usize = ready.len();
        pending.clear();
        ready.clear();
        *resident_bytes = 0;
        *cancelled_tasks = cancelled_tasks.saturating_add(dropped_pending as u64);
        *invalidated_artifacts = invalidated_artifacts.saturating_add(dropped_ready as u64);
        dropped_pending.saturating_add(dropped_ready)
    }

    /// Cancels all pending tasks and discards ready artifacts targeting `route_key`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `&str` - Route key to cancel.
    ///
    /// # Returns
    ///
    /// - `usize` - Total cancelled pending tasks and discarded artifacts for `route_key`.
    pub fn cancel_route(&mut self, route_key: &str) -> usize {
        let Self {
            pending,
            ready,
            resident_bytes,
            cancelled_tasks,
            invalidated_artifacts,
            ..
        } = self;
        let before_pending: usize = pending.len();
        pending.retain(|t: &RoutePrewarmTask| t.get_route_key().as_str() != route_key);
        let removed_pending: usize = before_pending.saturating_sub(pending.len());
        let mut removed_ready: usize = 0;
        let mut freed_bytes: usize = 0;
        ready.retain(|art: &PrewarmedRouteArtifact| {
            if art.get_route_key().as_str() == route_key {
                removed_ready += 1;
                freed_bytes = freed_bytes.saturating_add(art.get_resident_bytes());
                false
            } else {
                true
            }
        });
        *resident_bytes = resident_bytes.saturating_sub(freed_bytes);
        *cancelled_tasks = cancelled_tasks.saturating_add(removed_pending as u64);
        *invalidated_artifacts = invalidated_artifacts.saturating_add(removed_ready as u64);
        removed_pending.saturating_add(removed_ready)
    }

    /// Immediately cancels every pending pre-warm task and drops all ready speculative artifacts (e.g. under memory pressure).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    ///
    /// # Returns
    ///
    /// - `usize` - Total cancelled tasks and evicted artifacts.
    pub fn cancel_all(&mut self) -> usize {
        let Self {
            pending,
            ready,
            resident_bytes,
            cancelled_tasks,
            invalidated_artifacts,
            ..
        } = self;
        let p_len: usize = pending.len();
        let r_len: usize = ready.len();
        pending.clear();
        ready.clear();
        *resident_bytes = 0;
        *cancelled_tasks = cancelled_tasks.saturating_add(p_len as u64);
        *invalidated_artifacts = invalidated_artifacts.saturating_add(r_len as u64);
        p_len.saturating_add(r_len)
    }

    /// Executes queued pre-warm tasks strictly within `budget_us`, per-frame upload caps, and memory limits.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
    /// - `u64` - Remaining microsecond budget available on this frame (`0` uses `default_step_budget_us`).
    ///
    /// # Returns
    ///
    /// - `usize` - Number of tasks completed during this frame slice.
    pub fn step_budgeted(&mut self, active_context: PrewarmContextKey, budget_us: u64) -> usize {
        let _: usize = self.invalidate_context(active_context);
        if !self.get_enabled() || self.get_pending().is_empty() {
            return 0;
        }
        let max_us: u64 = if budget_us == 0 {
            self.get_default_step_budget_us()
        } else {
            budget_us
        };
        let max_upload: usize = self.get_max_upload_bytes_per_frame();
        let max_mem: usize = self.get_max_memory_bytes();
        let mut spent_us: u64 = 0;
        let mut spent_bytes: usize = 0;
        let mut completed: usize = 0;
        #[cfg(not(target_arch = "wasm32"))]
        let slice_start: Instant = Instant::now();
        while !self.get_pending().is_empty() {
            #[cfg(not(target_arch = "wasm32"))]
            if completed > 0 && (slice_start.elapsed().as_micros() as u64) >= max_us {
                let Self {
                    budget_deferrals, ..
                } = self;
                *budget_deferrals = budget_deferrals.saturating_add(1);
                break;
            }
            let next_us: u64 = self.get_pending()[0].get_estimated_us();
            let next_bytes: usize = self.get_pending()[0].get_estimated_bytes();
            let over_time: bool = spent_us.saturating_add(next_us) > max_us;
            let over_upload: bool = spent_bytes.saturating_add(next_bytes) > max_upload;
            if completed > 0 && (over_time || over_upload) {
                let Self {
                    budget_deferrals, ..
                } = self;
                *budget_deferrals = budget_deferrals.saturating_add(1);
                break;
            }
            if over_time && next_us > max_us {
                let Self {
                    budget_deferrals, ..
                } = self;
                *budget_deferrals = budget_deferrals.saturating_add(1);
                break;
            }
            let task: RoutePrewarmTask = self.get_mut_pending().remove(0);
            if task.get_context() != active_context {
                let Self {
                    cancelled_tasks, ..
                } = self;
                *cancelled_tasks = cancelled_tasks.saturating_add(1);
                continue;
            }
            if !task.get_sample_text().is_empty()
                && matches!(
                    task.get_kind(),
                    PrewarmWorkKind::TextShaping | PrewarmWorkKind::GlyphRaster
                )
            {
                let dpr: f32 = f32::from_bits(active_context.get_dpr_bits()).max(0.5);
                let warm_style: TextStyle = TextStyle::default();
                let phys_px: f32 = (warm_style.get_font_size() * dpr).max(8.0);
                for ch in task.get_sample_text().chars().take(32) {
                    if task.get_kind() == PrewarmWorkKind::GlyphRaster {
                        let key: GlyphKey = GlyphKey::from_text_style(ch, phys_px, warm_style);
                        let _: RasterizedGlyph = rasterize_glyph(key);
                    } else {
                        let _: f32 = measure_char_advance(ch, warm_style);
                    }
                }
            }
            let task_bytes: usize = task.get_estimated_bytes();
            let Self {
                ready,
                resident_bytes,
                executed_tasks,
                invalidated_artifacts,
                ..
            } = self;
            while !ready.is_empty() && resident_bytes.saturating_add(task_bytes) > max_mem {
                let evicted: PrewarmedRouteArtifact = ready.remove(0);
                *resident_bytes = resident_bytes.saturating_sub(evicted.get_resident_bytes());
                *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
            }
            let bit: u8 = 1_u8 << (task.get_kind() as u8);
            if let Some(existing) = ready.iter_mut().find(|art: &&mut PrewarmedRouteArtifact| {
                art.get_route_key() == task.get_route_key()
            }) {
                existing.set_completed_work_mask(existing.get_completed_work_mask() | bit);
                existing
                    .set_resident_bytes(existing.get_resident_bytes().saturating_add(task_bytes));
                existing.set_prepared_items(existing.get_prepared_items().saturating_add(1));
            } else {
                ready.push(PrewarmedRouteArtifact {
                    route_key: task.get_route_key().clone(),
                    context: active_context,
                    completed_work_mask: bit,
                    resident_bytes: task_bytes,
                    prepared_items: 1,
                });
            }
            *resident_bytes = resident_bytes.saturating_add(task_bytes);
            *executed_tasks = executed_tasks.saturating_add(1);
            spent_us = spent_us.saturating_add(next_us);
            spent_bytes = spent_bytes.saturating_add(task_bytes);
            completed += 1;
        }
        completed
    }

    /// Consumes and returns a ready pre-warmed artifact for `route_key` ONLY when its `(version, theme, DPR)` context matches `active_context`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable route pre-warmer.
    /// - `&str` - Route key being entered.
    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
    ///
    /// # Returns
    ///
    /// - `Option<PrewarmedRouteArtifact>` - Valid artifact if matched, or `None` if absent or stale.
    pub fn take_ready_artifact(
        &mut self,
        route_key: &str,
        active_context: PrewarmContextKey,
    ) -> Option<PrewarmedRouteArtifact> {
        let Self {
            ready,
            resident_bytes,
            invalidated_artifacts,
            ..
        } = self;
        let idx: usize = ready
            .iter()
            .position(|art: &PrewarmedRouteArtifact| art.get_route_key().as_str() == route_key)?;
        let artifact: PrewarmedRouteArtifact = ready.remove(idx);
        *resident_bytes = resident_bytes.saturating_sub(artifact.get_resident_bytes());
        if artifact.get_context() != active_context {
            *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
            return None;
        }
        Some(artifact)
    }
}

/// Cheap `Arc`-backed cloning for `BackgroundTask<T>` regardless of whether `T: Clone`.
impl<T> Clone for BackgroundTask<T> {
    /// Clones the shared task handle referencing the same completion flag and result slot.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Existing background task handle.
    ///
    /// # Returns
    ///
    /// - `Self` - Shared handle pointing to the same worker result.
    fn clone(&self) -> Self {
        let Self { ready, slot } = self;
        Self {
            ready: Arc::clone(ready),
            slot: Arc::clone(slot),
        }
    }
}

/// Non-blocking task spawning and lock-free completion polling for `BackgroundTask<T>`.
impl<T> BackgroundTask<T> {
    /// Wraps an already-computed value in an immediately ready `BackgroundTask<T>` with zero thread spawn.
    ///
    /// # Arguments
    ///
    /// - `T` - Precomputed payload ready for immediate consumption.
    ///
    /// # Returns
    ///
    /// - `Self` - Immediately ready task handle.
    #[must_use]
    pub fn ready(value: T) -> Self {
        Self {
            ready: Arc::new(AtomicBool::new(true)),
            slot: Arc::new(Mutex::new(Some(value))),
        }
    }

    /// Executes `work` on a background OS thread on native targets, or lazily inline on `wasm32`.
    ///
    /// # Arguments
    ///
    /// - `F` - Closure producing the background payload.
    ///
    /// # Returns
    ///
    /// - `Self` - Non-blocking handle polled via `is_ready` / `try_take`.
    #[must_use]
    pub fn spawn<F>(work: F) -> Self
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let ready: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
            let slot: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
            let ready_bg: Arc<AtomicBool> = Arc::clone(&ready);
            let slot_bg: Arc<Mutex<Option<T>>> = Arc::clone(&slot);
            let spawn_res: io::Result<JoinHandle<()>> = Builder::new()
                .name(PREWARM_BG_THREAD_NAME.to_string())
                .spawn(move || {
                    let value: T = work();
                    if let Ok(mut guard) = slot_bg.lock() {
                        *guard = Some(value);
                    }
                    ready_bg.store(true, Ordering::Release);
                });
            if spawn_res.is_err() {
                ready.store(true, Ordering::Release);
            }
            Self { ready, slot }
        }
        #[cfg(target_arch = "wasm32")]
        {
            let value: T = work();
            Self::ready(value)
        }
    }

    /// Returns `true` when the background computation has finished (single lock-free atomic load).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Task handle reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the payload is ready to take.
    #[must_use]
    pub fn is_ready(&self) -> bool {
        let Self { ready, .. } = self;
        ready.load(Ordering::Acquire)
    }

    /// Attempts to take the completed payload without blocking the UI thread.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Task handle reference.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Completed payload once ready, or `None` if still running or already consumed.
    #[must_use]
    pub fn try_take(&self) -> Option<T> {
        if !self.is_ready() {
            return None;
        }
        let Self { slot, .. } = self;
        match slot.lock() {
            Ok(mut guard) => guard.take(),
            Err(_) => None,
        }
    }

    /// Waits briefly until the background worker finishes and returns its payload.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Task handle reference.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Completed payload, or `None` if already consumed.
    #[must_use]
    pub fn take_blocking(&self) -> Option<T> {
        #[cfg(not(target_arch = "wasm32"))]
        while !self.is_ready() {
            sleep(Duration::from_micros(250));
        }
        self.try_take()
    }
}