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 h: u64 = FNV1A_OFFSET_BASIS;
20        for &b in locale.as_bytes().iter() {
21            h ^= b as u64;
22            h = h.wrapping_mul(FNV1A_PRIME);
23        }
24        if h == 0 { 1 } else { h }
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(|t: &RoutePrewarmTask| t.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(|t: &RoutePrewarmTask| t.get_route_key().as_str() != route_key);
383        let removed_pending: usize = before_pending.saturating_sub(pending.len());
384        let mut removed_ready: usize = 0;
385        let mut freed_bytes: usize = 0;
386        ready.retain(|art: &PrewarmedRouteArtifact| {
387            if art.get_route_key().as_str() == route_key {
388                removed_ready += 1;
389                freed_bytes = freed_bytes.saturating_add(art.get_resident_bytes());
390                false
391            } else {
392                true
393            }
394        });
395        *resident_bytes = resident_bytes.saturating_sub(freed_bytes);
396        *cancelled_tasks = cancelled_tasks.saturating_add(removed_pending as u64);
397        *invalidated_artifacts = invalidated_artifacts.saturating_add(removed_ready as u64);
398        removed_pending.saturating_add(removed_ready)
399    }
400
401    /// Immediately cancels every pending pre-warm task and drops all ready speculative artifacts (e.g. under memory pressure).
402    ///
403    /// # Arguments
404    ///
405    /// - `&Self` - Mutable route pre-warmer.
406    ///
407    /// # Returns
408    ///
409    /// - `usize` - Total cancelled tasks and evicted artifacts.
410    pub fn cancel_all(&mut self) -> usize {
411        let Self {
412            pending,
413            ready,
414            resident_bytes,
415            cancelled_tasks,
416            invalidated_artifacts,
417            ..
418        } = self;
419        let p_len: usize = pending.len();
420        let r_len: usize = ready.len();
421        pending.clear();
422        ready.clear();
423        *resident_bytes = 0;
424        *cancelled_tasks = cancelled_tasks.saturating_add(p_len as u64);
425        *invalidated_artifacts = invalidated_artifacts.saturating_add(r_len as u64);
426        p_len.saturating_add(r_len)
427    }
428
429    /// Executes queued pre-warm tasks strictly within `budget_us`, per-frame upload caps, and memory limits.
430    ///
431    /// # Arguments
432    ///
433    /// - `&Self` - Mutable route pre-warmer.
434    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
435    /// - `u64` - Remaining microsecond budget available on this frame (`0` uses `default_step_budget_us`).
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - Number of tasks completed during this frame slice.
440    pub fn step_budgeted(&mut self, active_context: PrewarmContextKey, budget_us: u64) -> usize {
441        let _: usize = self.invalidate_context(active_context);
442        if !self.get_enabled() || self.get_pending().is_empty() {
443            return 0;
444        }
445        let max_us: u64 = if budget_us == 0 {
446            self.get_default_step_budget_us()
447        } else {
448            budget_us
449        };
450        let max_upload: usize = self.get_max_upload_bytes_per_frame();
451        let max_mem: usize = self.get_max_memory_bytes();
452        let mut spent_us: u64 = 0;
453        let mut spent_bytes: usize = 0;
454        let mut completed: usize = 0;
455        #[cfg(not(target_arch = "wasm32"))]
456        let slice_start: Instant = Instant::now();
457        while !self.get_pending().is_empty() {
458            #[cfg(not(target_arch = "wasm32"))]
459            if completed > 0 && (slice_start.elapsed().as_micros() as u64) >= max_us {
460                let Self {
461                    budget_deferrals, ..
462                } = self;
463                *budget_deferrals = budget_deferrals.saturating_add(1);
464                break;
465            }
466            let next_us: u64 = self.get_pending()[0].get_estimated_us();
467            let next_bytes: usize = self.get_pending()[0].get_estimated_bytes();
468            let over_time: bool = spent_us.saturating_add(next_us) > max_us;
469            let over_upload: bool = spent_bytes.saturating_add(next_bytes) > max_upload;
470            if completed > 0 && (over_time || over_upload) {
471                let Self {
472                    budget_deferrals, ..
473                } = self;
474                *budget_deferrals = budget_deferrals.saturating_add(1);
475                break;
476            }
477            if over_time && next_us > max_us {
478                let Self {
479                    budget_deferrals, ..
480                } = self;
481                *budget_deferrals = budget_deferrals.saturating_add(1);
482                break;
483            }
484            let task: RoutePrewarmTask = self.get_mut_pending().remove(0);
485            if task.get_context() != active_context {
486                let Self {
487                    cancelled_tasks, ..
488                } = self;
489                *cancelled_tasks = cancelled_tasks.saturating_add(1);
490                continue;
491            }
492            if !task.get_sample_text().is_empty()
493                && matches!(
494                    task.get_kind(),
495                    PrewarmWorkKind::TextShaping | PrewarmWorkKind::GlyphRaster
496                )
497            {
498                let dpr: f32 = f32::from_bits(active_context.get_dpr_bits()).max(0.5);
499                let warm_style: TextStyle = TextStyle::default();
500                let phys_px: f32 = (warm_style.get_font_size() * dpr).max(8.0);
501                for ch in task.get_sample_text().chars().take(32) {
502                    if task.get_kind() == PrewarmWorkKind::GlyphRaster {
503                        let key: GlyphKey = GlyphKey::from_text_style(ch, phys_px, warm_style);
504                        let _: RasterizedGlyph = rasterize_glyph(key);
505                    } else {
506                        let _: f32 = measure_char_advance(ch, warm_style);
507                    }
508                }
509            }
510            let task_bytes: usize = task.get_estimated_bytes();
511            let Self {
512                ready,
513                resident_bytes,
514                executed_tasks,
515                invalidated_artifacts,
516                ..
517            } = self;
518            while !ready.is_empty() && resident_bytes.saturating_add(task_bytes) > max_mem {
519                let evicted: PrewarmedRouteArtifact = ready.remove(0);
520                *resident_bytes = resident_bytes.saturating_sub(evicted.get_resident_bytes());
521                *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
522            }
523            let bit: u8 = 1_u8 << (task.get_kind() as u8);
524            if let Some(existing) = ready.iter_mut().find(|art: &&mut PrewarmedRouteArtifact| {
525                art.get_route_key() == task.get_route_key()
526            }) {
527                existing.set_completed_work_mask(existing.get_completed_work_mask() | bit);
528                existing
529                    .set_resident_bytes(existing.get_resident_bytes().saturating_add(task_bytes));
530                existing.set_prepared_items(existing.get_prepared_items().saturating_add(1));
531            } else {
532                ready.push(PrewarmedRouteArtifact {
533                    route_key: task.get_route_key().clone(),
534                    context: active_context,
535                    completed_work_mask: bit,
536                    resident_bytes: task_bytes,
537                    prepared_items: 1,
538                });
539            }
540            *resident_bytes = resident_bytes.saturating_add(task_bytes);
541            *executed_tasks = executed_tasks.saturating_add(1);
542            spent_us = spent_us.saturating_add(next_us);
543            spent_bytes = spent_bytes.saturating_add(task_bytes);
544            completed += 1;
545        }
546        completed
547    }
548
549    /// Consumes and returns a ready pre-warmed artifact for `route_key` ONLY when its `(version, theme, DPR)` context matches `active_context`.
550    ///
551    /// # Arguments
552    ///
553    /// - `&Self` - Mutable route pre-warmer.
554    /// - `&str` - Route key being entered.
555    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
556    ///
557    /// # Returns
558    ///
559    /// - `Option<PrewarmedRouteArtifact>` - Valid artifact if matched, or `None` if absent or stale.
560    pub fn take_ready_artifact(
561        &mut self,
562        route_key: &str,
563        active_context: PrewarmContextKey,
564    ) -> Option<PrewarmedRouteArtifact> {
565        let Self {
566            ready,
567            resident_bytes,
568            invalidated_artifacts,
569            ..
570        } = self;
571        let idx: usize = ready
572            .iter()
573            .position(|art: &PrewarmedRouteArtifact| art.get_route_key().as_str() == route_key)?;
574        let artifact: PrewarmedRouteArtifact = ready.remove(idx);
575        *resident_bytes = resident_bytes.saturating_sub(artifact.get_resident_bytes());
576        if artifact.get_context() != active_context {
577            *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
578            return None;
579        }
580        Some(artifact)
581    }
582}
583
584/// Cheap `Arc`-backed cloning for `BackgroundTask<T>` regardless of whether `T: Clone`.
585impl<T> Clone for BackgroundTask<T> {
586    /// Clones the shared task handle referencing the same completion flag and result slot.
587    ///
588    /// # Arguments
589    ///
590    /// - `&Self` - Existing background task handle.
591    ///
592    /// # Returns
593    ///
594    /// - `Self` - Shared handle pointing to the same worker result.
595    fn clone(&self) -> Self {
596        let Self { ready, slot } = self;
597        Self {
598            ready: Arc::clone(ready),
599            slot: Arc::clone(slot),
600        }
601    }
602}
603
604/// Non-blocking task spawning and lock-free completion polling for `BackgroundTask<T>`.
605impl<T> BackgroundTask<T> {
606    /// Wraps an already-computed value in an immediately ready `BackgroundTask<T>` with zero thread spawn.
607    ///
608    /// # Arguments
609    ///
610    /// - `T` - Precomputed payload ready for immediate consumption.
611    ///
612    /// # Returns
613    ///
614    /// - `Self` - Immediately ready task handle.
615    #[must_use]
616    pub fn ready(value: T) -> Self {
617        Self {
618            ready: Arc::new(AtomicBool::new(true)),
619            slot: Arc::new(Mutex::new(Some(value))),
620        }
621    }
622
623    /// Executes `work` on a background OS thread on native targets, or lazily inline on `wasm32`.
624    ///
625    /// # Arguments
626    ///
627    /// - `F` - Closure producing the background payload.
628    ///
629    /// # Returns
630    ///
631    /// - `Self` - Non-blocking handle polled via `is_ready` / `try_take`.
632    #[must_use]
633    pub fn spawn<F>(work: F) -> Self
634    where
635        F: FnOnce() -> T + Send + 'static,
636        T: Send + 'static,
637    {
638        #[cfg(not(target_arch = "wasm32"))]
639        {
640            let ready: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
641            let slot: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
642            let ready_bg: Arc<AtomicBool> = Arc::clone(&ready);
643            let slot_bg: Arc<Mutex<Option<T>>> = Arc::clone(&slot);
644            let spawn_res: io::Result<JoinHandle<()>> = Builder::new()
645                .name(PREWARM_BG_THREAD_NAME.to_string())
646                .spawn(move || {
647                    let value: T = work();
648                    if let Ok(mut guard) = slot_bg.lock() {
649                        *guard = Some(value);
650                    }
651                    ready_bg.store(true, Ordering::Release);
652                });
653            if spawn_res.is_err() {
654                ready.store(true, Ordering::Release);
655            }
656            Self { ready, slot }
657        }
658        #[cfg(target_arch = "wasm32")]
659        {
660            let value: T = work();
661            Self::ready(value)
662        }
663    }
664
665    /// Returns `true` when the background computation has finished (single lock-free atomic load).
666    ///
667    /// # Arguments
668    ///
669    /// - `&Self` - Task handle reference.
670    ///
671    /// # Returns
672    ///
673    /// - `bool` - `true` if the payload is ready to take.
674    #[must_use]
675    pub fn is_ready(&self) -> bool {
676        let Self { ready, .. } = self;
677        ready.load(Ordering::Acquire)
678    }
679
680    /// Attempts to take the completed payload without blocking the UI thread.
681    ///
682    /// # Arguments
683    ///
684    /// - `&Self` - Task handle reference.
685    ///
686    /// # Returns
687    ///
688    /// - `Option<T>` - Completed payload once ready, or `None` if still running or already consumed.
689    #[must_use]
690    pub fn try_take(&self) -> Option<T> {
691        if !self.is_ready() {
692            return None;
693        }
694        let Self { slot, .. } = self;
695        match slot.lock() {
696            Ok(mut guard) => guard.take(),
697            Err(_) => None,
698        }
699    }
700
701    /// Waits briefly until the background worker finishes and returns its payload.
702    ///
703    /// # Arguments
704    ///
705    /// - `&Self` - Task handle reference.
706    ///
707    /// # Returns
708    ///
709    /// - `Option<T>` - Completed payload, or `None` if already consumed.
710    #[must_use]
711    pub fn take_blocking(&self) -> Option<T> {
712        #[cfg(not(target_arch = "wasm32"))]
713        while !self.is_ready() {
714            sleep(Duration::from_micros(250));
715        }
716        self.try_take()
717    }
718}