Skip to main content

euv_core/app/prewarm/
impl.rs

1use super::*;
2
3/// Constructor helpers for `PrewarmContextKey`.
4impl PrewarmContextKey {
5    /// Computes a deterministic 64-bit FNV-1a digest over a BCP-47 locale string (`0` for empty).
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - BCP-47 locale tag.
10    ///
11    /// # Returns
12    ///
13    /// - `u64` - Locale hash digest (`0` when `locale` is empty).
14    #[must_use]
15    pub fn hash_locale(locale: &str) -> u64 {
16        if locale.is_empty() {
17            return 0;
18        }
19        let mut height_val: u64 = FNV1A_OFFSET_BASIS;
20        for &blue_val in locale.as_bytes().iter() {
21            height_val ^= blue_val as u64;
22            height_val = height_val.wrapping_mul(FNV1A_PRIME);
23        }
24        if height_val == 0 { 1 } else { height_val }
25    }
26
27    /// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, and display `dpr`.
28    ///
29    /// # Arguments
30    ///
31    /// - `u64` - Application or bundle resource version.
32    /// - `ThemeMode` - Active light or dark theme mode.
33    /// - `f32` - Active display scale factor.
34    ///
35    /// # Returns
36    ///
37    /// - `Self` - Normalized context key.
38    #[must_use]
39    pub fn from_context(resource_version: u64, theme_mode: ThemeMode, dpr: f32) -> Self {
40        Self {
41            resource_version,
42            theme_mode,
43            dpr_bits: dpr.max(0.5).to_bits(),
44            locale_hash: 0,
45        }
46    }
47
48    /// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, `dpr`, and `locale`.
49    ///
50    /// # Arguments
51    ///
52    /// - `u64` - Application or bundle resource version.
53    /// - `ThemeMode` - Active light or dark theme mode.
54    /// - `f32` - Active display scale factor.
55    /// - `&str` - Active BCP-47 locale tag.
56    ///
57    /// # Returns
58    ///
59    /// - `Self` - Normalized full context key.
60    #[must_use]
61    pub fn from_full_context(
62        resource_version: u64,
63        theme_mode: ThemeMode,
64        dpr: f32,
65        locale: &str,
66    ) -> Self {
67        Self {
68            resource_version,
69            theme_mode,
70            dpr_bits: dpr.max(0.5).to_bits(),
71            locale_hash: Self::hash_locale(locale),
72        }
73    }
74
75    /// Returns a copy of this context key updated with the hashed `locale` tag.
76    ///
77    /// # Arguments
78    ///
79    /// - `Self` - Base context key.
80    /// - `&str` - Active BCP-47 locale tag.
81    ///
82    /// # Returns
83    ///
84    /// - `Self` - Updated context key bound to `locale`.
85    #[must_use]
86    pub fn with_locale(mut self, locale: &str) -> Self {
87        self.set_locale_hash(Self::hash_locale(locale));
88        self
89    }
90}
91
92/// Builder helpers for `RoutePrewarmTask`.
93impl RoutePrewarmTask {
94    /// Creates a new bounded route pre-warm task descriptor.
95    ///
96    /// # Arguments
97    ///
98    /// - `String` - Target route key.
99    /// - `PrewarmWorkKind` - Pre-warm phase kind.
100    /// - `PrewarmContextKey` - Active context signature `(version, theme, DPR, locale)`.
101    /// - `usize` - Estimated memory/upload footprint in bytes.
102    /// - `u64` - Estimated execution cost in microseconds.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Ready pre-warm task descriptor with default priority `1`.
107    #[must_use]
108    pub fn new(
109        route_key: String,
110        kind: PrewarmWorkKind,
111        context: PrewarmContextKey,
112        estimated_bytes: usize,
113        estimated_us: u64,
114    ) -> Self {
115        Self {
116            route_key,
117            kind,
118            context,
119            estimated_bytes,
120            estimated_us: estimated_us.max(1),
121            priority: 1,
122            sample_text: String::new(),
123        }
124    }
125
126    /// Sets task execution priority (`0` = highest).
127    ///
128    /// # Arguments
129    ///
130    /// - `Self` - Base task descriptor.
131    /// - `u8` - Priority level (`0` executes first).
132    ///
133    /// # Returns
134    ///
135    /// - `Self` - Updated task descriptor.
136    #[must_use]
137    pub fn with_priority(mut self, priority: u8) -> Self {
138        self.set_priority(priority);
139        self
140    }
141
142    /// Attaches representative route text so idle `TextShaping`/`GlyphRaster` slices warm the shared shaping cache.
143    ///
144    /// # Arguments
145    ///
146    /// - `Self` - Base task descriptor.
147    /// - `String` - Sample route heading or copy to warm.
148    ///
149    /// # Returns
150    ///
151    /// - `Self` - Updated task descriptor.
152    #[must_use]
153    pub fn with_sample_text(mut self, sample_text: String) -> Self {
154        self.set_sample_text(sample_text);
155        self
156    }
157}
158
159/// Default bounded `RoutePrewarmer` initialized with conservative memory and per-frame slice caps.
160impl Default for RoutePrewarmer {
161    /// Creates a default `RoutePrewarmer` with 32 max tasks, 8 MiB memory cap, and 1 MiB/frame upload cap.
162    ///
163    /// # Returns
164    ///
165    /// - `Self` - Ready route pre-warmer.
166    fn default() -> Self {
167        Self::with_limits(
168            PREWARM_DEFAULT_MAX_TASKS,
169            PREWARM_DEFAULT_MAX_MEMORY_BYTES,
170            PREWARM_DEFAULT_MAX_UPLOAD_PER_FRAME,
171        )
172    }
173}
174
175/// Bounded queueing, budgeted slicing, context invalidation, and cancellation for `RoutePrewarmer`.
176impl RoutePrewarmer {
177    /// Creates a `RoutePrewarmer` with explicit queue, memory, and per-frame upload byte caps.
178    ///
179    /// # Arguments
180    ///
181    /// - `usize` - Maximum pending tasks (`>= 1`).
182    /// - `usize` - Maximum aggregate artifact memory in bytes (`>= 4096`).
183    /// - `usize` - Maximum bytes uploaded/processed per budgeted frame step (`>= 4096`).
184    ///
185    /// # Returns
186    ///
187    /// - `Self` - Configured route pre-warmer.
188    #[must_use]
189    pub fn with_limits(
190        max_pending_tasks: usize,
191        max_memory_bytes: usize,
192        max_upload_bytes_per_frame: usize,
193    ) -> Self {
194        Self {
195            max_pending_tasks: max_pending_tasks.max(1),
196            max_memory_bytes: max_memory_bytes.max(4096),
197            max_upload_bytes_per_frame: max_upload_bytes_per_frame.max(4096),
198            default_step_budget_us: PREWARM_DEFAULT_STEP_BUDGET_US,
199            active_context: PrewarmContextKey::from_context(1, ThemeMode::Light, 1.0),
200            enabled: true,
201            pending: Vec::new(),
202            ready: Vec::new(),
203            resident_bytes: 0,
204            enqueued_count: 0,
205            executed_tasks: 0,
206            cancelled_tasks: 0,
207            invalidated_artifacts: 0,
208            budget_deferrals: 0,
209            preempted_until_idle: false,
210            idle_slices_executed: 0,
211        }
212    }
213
214    /// Preempts speculative route pre-warming immediately when user input or navigation begins.
215    ///
216    /// # Arguments
217    ///
218    /// - `&Self` - Mutable route pre-warmer.
219    pub fn preempt(&mut self) {
220        let Self {
221            preempted_until_idle,
222            ..
223        } = self;
224        *preempted_until_idle = true;
225    }
226
227    /// Executes real time-sliced post-Frame-1 idle pre-warming strictly within `<= 500 us` and yields immediately on input or navigation.
228    ///
229    /// # Arguments
230    ///
231    /// - `&Self` - Mutable route pre-warmer.
232    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR, locale)` context.
233    /// - `u64` - Foreground frame CPU duration already spent in microseconds.
234    /// - `bool` - True when user input, scrolling, or navigation occurred on this frame.
235    ///
236    /// # Returns
237    ///
238    /// - `usize` - Number of pre-warm tasks completed during this idle slice.
239    pub fn step_idle_post_frame1(
240        &mut self,
241        active_context: PrewarmContextKey,
242        frame_work_us: u64,
243        had_input_or_nav: bool,
244    ) -> usize {
245        if had_input_or_nav {
246            self.preempt();
247            return 0;
248        }
249        if !self.get_enabled() || self.get_pending().is_empty() {
250            let Self {
251                preempted_until_idle,
252                ..
253            } = self;
254            *preempted_until_idle = false;
255            return 0;
256        }
257        if self.get_preempted_until_idle() {
258            let Self {
259                preempted_until_idle,
260                ..
261            } = self;
262            *preempted_until_idle = false;
263            return 0;
264        }
265        let max_slice_us: u64 = self
266            .get_default_step_budget_us()
267            .min(PREWARM_DEFAULT_STEP_BUDGET_US);
268        let remaining_us: u64 = max_slice_us.saturating_sub(frame_work_us);
269        if remaining_us == 0 {
270            return 0;
271        }
272        let done: usize = self.step_budgeted(active_context, remaining_us);
273        if done > 0 {
274            let Self {
275                idle_slices_executed,
276                ..
277            } = self;
278            *idle_slices_executed = idle_slices_executed.saturating_add(1);
279        }
280        done
281    }
282
283    /// Enqueues `task` if pre-warming is enabled, context matches, queue has capacity, and no duplicate `(route, kind)` exists.
284    ///
285    /// # Arguments
286    ///
287    /// - `&Self` - Mutable route pre-warmer.
288    /// - `RoutePrewarmTask` - Candidate pre-warm task.
289    ///
290    /// # Returns
291    ///
292    /// - `bool` - `true` if accepted into the bounded queue.
293    pub fn enqueue(&mut self, task: RoutePrewarmTask) -> bool {
294        if !self.get_enabled() {
295            return false;
296        }
297        if task.get_context() != self.get_active_context() {
298            let Self {
299                cancelled_tasks, ..
300            } = self;
301            *cancelled_tasks = cancelled_tasks.saturating_add(1);
302            return false;
303        }
304        if self.get_pending().len() >= self.get_max_pending_tasks() {
305            return false;
306        }
307        let duplicate: bool = self
308            .get_pending()
309            .iter()
310            .any(|existing: &RoutePrewarmTask| {
311                existing.get_route_key() == task.get_route_key()
312                    && existing.get_kind() == task.get_kind()
313            });
314        if duplicate {
315            return false;
316        }
317        let Self {
318            pending,
319            enqueued_count,
320            ..
321        } = self;
322        pending.push(task);
323        pending.sort_by_key(|blend_factor: &RoutePrewarmTask| blend_factor.get_priority());
324        *enqueued_count = enqueued_count.saturating_add(1);
325        true
326    }
327
328    /// Invalidates all pending tasks and ready artifacts when `(resource_version, theme_mode, dpr)` changes.
329    ///
330    /// # Arguments
331    ///
332    /// - `&Self` - Mutable route pre-warmer.
333    /// - `PrewarmContextKey` - Newly active `(version, theme, DPR)` context key.
334    ///
335    /// # Returns
336    ///
337    /// - `usize` - Total stale pending tasks plus invalidated ready artifacts discarded.
338    pub fn invalidate_context(&mut self, next_context: PrewarmContextKey) -> usize {
339        if self.get_active_context() == next_context {
340            return 0;
341        }
342        let Self {
343            active_context,
344            pending,
345            ready,
346            resident_bytes,
347            cancelled_tasks,
348            invalidated_artifacts,
349            ..
350        } = self;
351        *active_context = next_context;
352        let dropped_pending: usize = pending.len();
353        let dropped_ready: usize = ready.len();
354        pending.clear();
355        ready.clear();
356        *resident_bytes = 0;
357        *cancelled_tasks = cancelled_tasks.saturating_add(dropped_pending as u64);
358        *invalidated_artifacts = invalidated_artifacts.saturating_add(dropped_ready as u64);
359        dropped_pending.saturating_add(dropped_ready)
360    }
361
362    /// Cancels all pending tasks and discards ready artifacts targeting `route_key`.
363    ///
364    /// # Arguments
365    ///
366    /// - `&Self` - Mutable route pre-warmer.
367    /// - `&str` - Route key to cancel.
368    ///
369    /// # Returns
370    ///
371    /// - `usize` - Total cancelled pending tasks and discarded artifacts for `route_key`.
372    pub fn cancel_route(&mut self, route_key: &str) -> usize {
373        let Self {
374            pending,
375            ready,
376            resident_bytes,
377            cancelled_tasks,
378            invalidated_artifacts,
379            ..
380        } = self;
381        let before_pending: usize = pending.len();
382        pending.retain(|blend_factor: &RoutePrewarmTask| {
383            blend_factor.get_route_key().as_str() != route_key
384        });
385        let removed_pending: usize = before_pending.saturating_sub(pending.len());
386        let mut removed_ready: usize = 0;
387        let mut freed_bytes: usize = 0;
388        ready.retain(|art: &PrewarmedRouteArtifact| {
389            if art.get_route_key().as_str() == route_key {
390                removed_ready += 1;
391                freed_bytes = freed_bytes.saturating_add(art.get_resident_bytes());
392                false
393            } else {
394                true
395            }
396        });
397        *resident_bytes = resident_bytes.saturating_sub(freed_bytes);
398        *cancelled_tasks = cancelled_tasks.saturating_add(removed_pending as u64);
399        *invalidated_artifacts = invalidated_artifacts.saturating_add(removed_ready as u64);
400        removed_pending.saturating_add(removed_ready)
401    }
402
403    /// Immediately cancels every pending pre-warm task and drops all ready speculative artifacts (e.g. under memory pressure).
404    ///
405    /// # Arguments
406    ///
407    /// - `&Self` - Mutable route pre-warmer.
408    ///
409    /// # Returns
410    ///
411    /// - `usize` - Total cancelled tasks and evicted artifacts.
412    pub fn cancel_all(&mut self) -> usize {
413        let Self {
414            pending,
415            ready,
416            resident_bytes,
417            cancelled_tasks,
418            invalidated_artifacts,
419            ..
420        } = self;
421        let p_len: usize = pending.len();
422        let r_len: usize = ready.len();
423        pending.clear();
424        ready.clear();
425        *resident_bytes = 0;
426        *cancelled_tasks = cancelled_tasks.saturating_add(p_len as u64);
427        *invalidated_artifacts = invalidated_artifacts.saturating_add(r_len as u64);
428        p_len.saturating_add(r_len)
429    }
430
431    /// Executes queued pre-warm tasks strictly within `budget_us`, per-frame upload caps, and memory limits.
432    ///
433    /// # Arguments
434    ///
435    /// - `&Self` - Mutable route pre-warmer.
436    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
437    /// - `u64` - Remaining microsecond budget available on this frame (`0` uses `default_step_budget_us`).
438    ///
439    /// # Returns
440    ///
441    /// - `usize` - Number of tasks completed during this frame slice.
442    pub fn step_budgeted(&mut self, active_context: PrewarmContextKey, budget_us: u64) -> usize {
443        let _: usize = self.invalidate_context(active_context);
444        if !self.get_enabled() || self.get_pending().is_empty() {
445            return 0;
446        }
447        let max_us: u64 = if budget_us == 0 {
448            self.get_default_step_budget_us()
449        } else {
450            budget_us
451        };
452        let max_upload: usize = self.get_max_upload_bytes_per_frame();
453        let max_mem: usize = self.get_max_memory_bytes();
454        let mut spent_us: u64 = 0;
455        let mut spent_bytes: usize = 0;
456        let mut completed: usize = 0;
457        #[cfg(not(target_arch = "wasm32"))]
458        let slice_start: Instant = Instant::now();
459        while !self.get_pending().is_empty() {
460            #[cfg(not(target_arch = "wasm32"))]
461            if completed > 0 && (slice_start.elapsed().as_micros() as u64) >= max_us {
462                let Self {
463                    budget_deferrals, ..
464                } = self;
465                *budget_deferrals = budget_deferrals.saturating_add(1);
466                break;
467            }
468            let next_us: u64 = self.get_pending()[0].get_estimated_us();
469            let next_bytes: usize = self.get_pending()[0].get_estimated_bytes();
470            let over_time: bool = spent_us.saturating_add(next_us) > max_us;
471            let over_upload: bool = spent_bytes.saturating_add(next_bytes) > max_upload;
472            if completed > 0 && (over_time || over_upload) {
473                let Self {
474                    budget_deferrals, ..
475                } = self;
476                *budget_deferrals = budget_deferrals.saturating_add(1);
477                break;
478            }
479            if over_time && next_us > max_us {
480                let Self {
481                    budget_deferrals, ..
482                } = self;
483                *budget_deferrals = budget_deferrals.saturating_add(1);
484                break;
485            }
486            let task: RoutePrewarmTask = self.get_mut_pending().remove(0);
487            if task.get_context() != active_context {
488                let Self {
489                    cancelled_tasks, ..
490                } = self;
491                *cancelled_tasks = cancelled_tasks.saturating_add(1);
492                continue;
493            }
494            if task.get_kind() == PrewarmWorkKind::PipelineWarmup {
495                precompile_shaders_async(default_native_gpu_backend());
496            } else if !task.get_sample_text().is_empty()
497                && matches!(
498                    task.get_kind(),
499                    PrewarmWorkKind::TextShaping | PrewarmWorkKind::GlyphRaster
500                )
501            {
502                let dpr: f32 = f32::from_bits(active_context.get_dpr_bits()).max(0.5);
503                let warm_style: TextStyle = TextStyle::default();
504                let phys_px: f32 = (warm_style.get_font_size() * dpr).max(8.0);
505                for ch in task.get_sample_text().chars().take(32) {
506                    if task.get_kind() == PrewarmWorkKind::GlyphRaster {
507                        let key: GlyphKey = GlyphKey::from_text_style(ch, phys_px, warm_style);
508                        let _: RasterizedGlyph = rasterize_glyph(key);
509                    } else {
510                        let _: f32 = measure_char_advance(ch, warm_style);
511                    }
512                }
513            }
514            let task_bytes: usize = task.get_estimated_bytes();
515            let Self {
516                ready,
517                resident_bytes,
518                executed_tasks,
519                invalidated_artifacts,
520                ..
521            } = self;
522            while !ready.is_empty() && resident_bytes.saturating_add(task_bytes) > max_mem {
523                let evicted: PrewarmedRouteArtifact = ready.remove(0);
524                *resident_bytes = resident_bytes.saturating_sub(evicted.get_resident_bytes());
525                *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
526            }
527            let bit: u8 = 1_u8 << (task.get_kind() as u8);
528            if let Some(existing) = ready.iter_mut().find(|art: &&mut PrewarmedRouteArtifact| {
529                art.get_route_key() == task.get_route_key()
530            }) {
531                existing.set_completed_work_mask(existing.get_completed_work_mask() | bit);
532                existing
533                    .set_resident_bytes(existing.get_resident_bytes().saturating_add(task_bytes));
534                existing.set_prepared_items(existing.get_prepared_items().saturating_add(1));
535            } else {
536                ready.push(PrewarmedRouteArtifact {
537                    route_key: task.get_route_key().clone(),
538                    context: active_context,
539                    completed_work_mask: bit,
540                    resident_bytes: task_bytes,
541                    prepared_items: 1,
542                });
543            }
544            *resident_bytes = resident_bytes.saturating_add(task_bytes);
545            *executed_tasks = executed_tasks.saturating_add(1);
546            spent_us = spent_us.saturating_add(next_us);
547            spent_bytes = spent_bytes.saturating_add(task_bytes);
548            completed += 1;
549        }
550        completed
551    }
552
553    /// Consumes and returns a ready pre-warmed artifact for `route_key` ONLY when its `(version, theme, DPR)` context matches `active_context`.
554    ///
555    /// # Arguments
556    ///
557    /// - `&Self` - Mutable route pre-warmer.
558    /// - `&str` - Route key being entered.
559    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
560    ///
561    /// # Returns
562    ///
563    /// - `Option<PrewarmedRouteArtifact>` - Valid artifact if matched, or `None` if absent or stale.
564    pub fn take_ready_artifact(
565        &mut self,
566        route_key: &str,
567        active_context: PrewarmContextKey,
568    ) -> Option<PrewarmedRouteArtifact> {
569        let Self {
570            ready,
571            resident_bytes,
572            invalidated_artifacts,
573            ..
574        } = self;
575        let idx: usize = ready
576            .iter()
577            .position(|art: &PrewarmedRouteArtifact| art.get_route_key().as_str() == route_key)?;
578        let artifact: PrewarmedRouteArtifact = ready.remove(idx);
579        *resident_bytes = resident_bytes.saturating_sub(artifact.get_resident_bytes());
580        if artifact.get_context() != active_context {
581            *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
582            return None;
583        }
584        Some(artifact)
585    }
586}
587
588/// Cheap `Arc`-backed cloning for `BackgroundTask<T>` regardless of whether `T: Clone`.
589impl<ValueType> Clone for BackgroundTask<ValueType> {
590    /// Clones the shared task handle referencing the same completion flag and result slot.
591    ///
592    /// # Arguments
593    ///
594    /// - `&Self` - Existing background task handle.
595    ///
596    /// # Returns
597    ///
598    /// - `Self` - Shared handle pointing to the same worker result.
599    fn clone(&self) -> Self {
600        let Self { ready, slot } = self;
601        Self {
602            ready: Arc::clone(ready),
603            slot: Arc::clone(slot),
604        }
605    }
606}
607
608/// Non-blocking task spawning and lock-free completion polling for `BackgroundTask<T>`.
609impl<ValueType> BackgroundTask<ValueType> {
610    /// Wraps an already-computed value in an immediately ready `BackgroundTask<T>` with zero thread spawn.
611    ///
612    /// # Arguments
613    ///
614    /// - `ValueType` - Precomputed payload ready for immediate consumption.
615    ///
616    /// # Returns
617    ///
618    /// - `Self` - Immediately ready task handle.
619    #[must_use]
620    pub fn ready(value: ValueType) -> Self {
621        Self {
622            ready: Arc::new(AtomicBool::new(true)),
623            slot: Arc::new(Mutex::new(Some(value))),
624        }
625    }
626
627    /// Executes `work` on a background OS thread on native targets, or lazily inline on `wasm32`.
628    ///
629    /// # Arguments
630    ///
631    /// - `CallbackFn` - Closure producing the background payload.
632    ///
633    /// # Returns
634    ///
635    /// - `Self` - Non-blocking handle polled via `is_ready` / `try_take`.
636    #[must_use]
637    pub fn spawn<CallbackFn>(work: CallbackFn) -> Self
638    where
639        CallbackFn: FnOnce() -> ValueType + Send + 'static,
640        ValueType: Send + 'static,
641    {
642        #[cfg(not(target_arch = "wasm32"))]
643        {
644            let ready: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
645            let slot: Arc<Mutex<Option<ValueType>>> = Arc::new(Mutex::new(None));
646            let ready_bg: Arc<AtomicBool> = Arc::clone(&ready);
647            let slot_bg: Arc<Mutex<Option<ValueType>>> = Arc::clone(&slot);
648            let spawn_res: io::Result<JoinHandle<()>> = Builder::new()
649                .name(PREWARM_BG_THREAD_NAME.to_string())
650                .spawn(move || {
651                    let value: ValueType = work();
652                    if let Ok(mut guard) = slot_bg.lock() {
653                        *guard = Some(value);
654                    }
655                    ready_bg.store(true, Ordering::Release);
656                });
657            if spawn_res.is_err() {
658                ready.store(true, Ordering::Release);
659            }
660            Self { ready, slot }
661        }
662        #[cfg(target_arch = "wasm32")]
663        {
664            let value: ValueType = work();
665            Self::ready(value)
666        }
667    }
668
669    /// Returns `true` when the background computation has finished (single lock-free atomic load).
670    ///
671    /// # Arguments
672    ///
673    /// - `&Self` - Task handle reference.
674    ///
675    /// # Returns
676    ///
677    /// - `bool` - `true` if the payload is ready to take.
678    #[must_use]
679    pub fn is_ready(&self) -> bool {
680        let Self { ready, .. } = self;
681        ready.load(Ordering::Acquire)
682    }
683
684    /// Attempts to take the completed payload without blocking the UI thread.
685    ///
686    /// # Arguments
687    ///
688    /// - `&Self` - Task handle reference.
689    ///
690    /// # Returns
691    ///
692    /// - `Option<ValueType>` - Completed payload once ready, or `None` if still running or already consumed.
693    #[must_use]
694    pub fn try_take(&self) -> Option<ValueType> {
695        if !self.is_ready() {
696            return None;
697        }
698        let Self { slot, .. } = self;
699        match slot.lock() {
700            Ok(mut guard) => guard.take(),
701            Err(_) => None,
702        }
703    }
704
705    /// Waits briefly until the background worker finishes and returns its payload.
706    ///
707    /// # Arguments
708    ///
709    /// - `&Self` - Task handle reference.
710    ///
711    /// # Returns
712    ///
713    /// - `Option<ValueType>` - Completed payload, or `None` if already consumed.
714    #[must_use]
715    pub fn take_blocking(&self) -> Option<ValueType> {
716        #[cfg(not(target_arch = "wasm32"))]
717        while !self.is_ready() {
718            sleep(Duration::from_micros(250));
719        }
720        self.try_take()
721    }
722}