some_executor 0.7.2

A trait for libraries that abstract over any executor
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Thread-local storage for executors.
//!
//! This module provides a mechanism to associate executors with specific threads,
//! allowing async code to spawn tasks without explicitly passing executor references.
//! Thread-local executors serve as a fallback in the executor discovery hierarchy,
//! sitting between task-specific executors and the global executor.
//!
//! # Overview
//!
//! The module supports three types of thread-local executors:
//!
//! - **Regular executors** (`DynExecutor`): Can spawn `Send` futures and are typically
//!   used when the executor can move work between threads.
//! - **Local executors** (`SomeLocalExecutor`): Can spawn `!Send` futures and execute
//!   them on the current thread only.
//! - **Static executors** (`SomeStaticExecutor`): Can spawn `'static` futures that do not
//!   need to be `Send`, suitable for static data with thread-local execution.
//!
//! # Usage in Executor Discovery
//!
//! Thread-local executors are part of the executor discovery hierarchy used by
//! [`current_executor`](crate::current_executor::current_executor):
//!
//! 1. Task executor (highest priority)
//! 2. **Thread executor** (this module)
//! 3. Global executor
//! 4. Last resort executor (lowest priority)
//!
//! # Examples
//!
//! ## Setting a thread executor
//!
//! ```
//! use some_executor::thread_executor::{set_thread_executor, thread_executor};
//!
//! # fn example() {
//! # let my_executor: Box<some_executor::DynExecutor> = todo!();
//! // Set an executor for the current thread
//! set_thread_executor(my_executor);
//!
//! // Later, access the thread executor
//! thread_executor(|executor| {
//!     if let Some(exec) = executor {
//!         println!("Thread has an executor");
//!     }
//! });
//! # }
//! ```
//!
//! ## Setting a thread-static executor
//!
//! ```
//! use some_executor::thread_executor::{set_thread_static_executor, thread_static_executor};
//!
//! # fn example() {
//! # let my_static_executor: Box<dyn some_executor::SomeStaticExecutor<ExecutorNotifier = Box<dyn some_executor::observer::ExecutorNotified>>> = todo!();
//! // Set a static executor for the current thread
//! set_thread_static_executor(my_static_executor);
//!
//! // Later, access the thread-static executor (always returns a valid executor)
//! thread_static_executor(|executor| {
//!     // executor is always valid - either user-provided or last resort
//!     println!("Thread has a static executor");
//! });
//! # }
//! ```
//!
//! ## Using thread-local executors with current_executor
//!
//! ```
//! use some_executor::thread_executor::set_thread_executor;
//! use some_executor::current_executor::current_executor;
//! use some_executor::SomeExecutor;
//! use some_executor::task::{Task, Configuration};
//! use some_executor::observer::Observer;
//!
//! # async fn example() {
//! # let my_executor: Box<some_executor::DynExecutor> = todo!();
//! // Set a thread-local executor
//! set_thread_executor(my_executor);
//!
//! // current_executor will find and use the thread-local executor
//! let mut executor = current_executor();
//!
//! let task = Task::without_notifications(
//!     "example".to_string(),
//!     Configuration::default(),
//!     async { println!("Running on thread executor"); },
//! );
//!
//! executor.spawn(task).detach();
//! # }
//! ```
//!
//! # Thread Safety
//!
//! Thread-local storage is inherently thread-safe as each thread has its own
//! independent storage. However, the executors themselves must be `Send + Sync`
//! for regular executors, as they may be cloned and shared across async contexts.

use crate::observer::ExecutorNotified;
use crate::task::Configuration;
use crate::{DynExecutor, SomeLocalExecutor, SomeStaticExecutor};
use std::cell::RefCell;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::rc::Rc;
// Type alias for complex types to satisfy clippy::type_complexity warnings

/// Type alias for a thread-local executor that can handle local tasks
type ThreadLocalExecutor = RefCell<
    Option<
        Rc<
            RefCell<
                Box<dyn SomeLocalExecutor<'static, ExecutorNotifier = Box<dyn ExecutorNotified>>>,
            >,
        >,
    >,
>;

/// Type alias for a thread-static executor that can handle static tasks
type ThreadStaticExecutor =
    RefCell<Option<Box<dyn SomeStaticExecutor<ExecutorNotifier = Box<dyn ExecutorNotified>>>>>;

thread_local! {
    static THREAD_EXECUTOR: RefCell<Option<Box<DynExecutor>>> = RefCell::new(None);
    static THREAD_LOCAL_EXECUTOR: ThreadLocalExecutor = RefCell::new(None);
    static THREAD_STATIC_EXECUTOR: ThreadStaticExecutor = RefCell::new(None);
}

/// Accesses the executor that is available for the current thread.
///
/// This function provides safe access to the thread-local executor, if one has been set.
/// The executor is accessed through a closure to ensure proper borrowing semantics.
///
/// # Parameters
///
/// - `c`: A closure that receives an optional reference to the thread's executor.
///   The closure should return a value of type `R`.
///
/// # Returns
///
/// Returns whatever value the closure produces.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::{thread_executor, set_thread_executor};
///
/// # fn example() {
/// // Check if thread has an executor
/// let has_executor = thread_executor(|exec| exec.is_some());
/// println!("Thread has executor: {}", has_executor);
///
/// # let my_executor: Box<some_executor::DynExecutor> = todo!();
/// // Set an executor
/// set_thread_executor(my_executor);
///
/// // Clone the executor for use elsewhere
/// let cloned = thread_executor(|exec| {
///     exec.map(|e| e.clone_box())
/// });
/// # }
/// ```
///
/// # Panics
///
/// The thread's executor slot is borrowed while the closure runs; calling
/// [`set_thread_executor`] from within the closure panics.
pub fn thread_executor<R>(c: impl FnOnce(Option<&DynExecutor>) -> R) -> R {
    THREAD_EXECUTOR.with(|e| c(e.borrow().as_ref().map(|e| &**e)))
}

/// Sets the executor for the current thread.
///
/// This function associates an executor with the current thread. Once set, this
/// executor will be available to async code running on this thread through
/// [`thread_executor`] or [`current_executor`](crate::current_executor::current_executor).
///
/// # Parameters
///
/// - `runtime`: A boxed executor that implements the `SomeExecutor` trait.
///   This executor will be stored in thread-local storage.
///
/// # Note
///
/// Setting a new executor will replace any previously set executor for this thread,
/// permanently: this function is one-way, and there is no way to "unset" an executor
/// afterwards.  If you want the install to end -- restoring whatever was there before,
/// including nothing -- use [`install_thread_executor`] and hold its guard.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::{set_thread_executor, thread_executor};
///
/// # fn example() {
/// # let executor: Box<some_executor::DynExecutor> = todo!();
/// // Set a thread-local executor
/// set_thread_executor(executor);
///
/// // Verify it was set
/// thread_executor(|exec| {
///     assert!(exec.is_some());
/// });
/// # }
/// ```
///
/// ## Use with async runtimes
///
/// ```
/// use some_executor::thread_executor::set_thread_executor;
///
/// # async fn example() {
/// # let runtime_executor: Box<some_executor::DynExecutor> = todo!();
/// // Set up a thread-local executor when initializing a worker thread
/// std::thread::spawn(move || {
///     set_thread_executor(runtime_executor);
///
///     // Now any async code on this thread can access the executor
///     // through current_executor() or thread_executor()
/// });
/// # }
/// ```
pub fn set_thread_executor(runtime: Box<DynExecutor>) {
    THREAD_EXECUTOR.with(|e| {
        *e.borrow_mut() = Some(runtime);
    });
}

/// Swaps the thread's executor, returning the one that was there.
///
/// The primitive under [`install_thread_executor`], which is the public way to do this.
pub(crate) fn replace_thread_executor(
    runtime: Option<Box<DynExecutor>>,
) -> Option<Box<DynExecutor>> {
    THREAD_EXECUTOR.with(|e| std::mem::replace(&mut *e.borrow_mut(), runtime))
}

/// Installs `runtime` as this thread's executor until the returned guard is dropped.
///
/// This is the reversible counterpart of [`set_thread_executor`], which is one-way.  It
/// exists because [`SomeExecutor::block_on`](crate::SomeExecutor::block_on) promises that
/// the executor is current for the duration of the block and no longer, and a backend
/// that overrides [`block_on_objsafe`](crate::SomeExecutor::block_on_objsafe) -- which
/// current-thread and ambient-context backends must -- has to be able to keep that
/// promise too.
///
/// Rolling this by hand with [`thread_executor`] and [`set_thread_executor`] does not
/// work.  It costs a `clone_box` of whatever was displaced, and more importantly there is
/// no way to put the *empty* state back: a thread that had no executor before the call
/// silently keeps one afterwards, so [`current_executor`](crate::current_executor::current_executor)
/// starts answering differently.  The guard restores `None` as readily as it restores an
/// executor.
///
/// # Examples
///
/// ```
/// use some_executor::current_executor::current_executor;
/// use some_executor::thread_executor::{install_thread_executor, thread_executor};
///
/// let before = thread_executor(|e| e.is_some());
/// {
///     let _guard = install_thread_executor(current_executor());
///     assert!(thread_executor(|e| e.is_some()));
/// }
/// // Whatever was there before is back -- including nothing at all.
/// assert_eq!(thread_executor(|e| e.is_some()), before);
/// ```
///
/// # Nesting and unwinding
///
/// The guard restores on drop, so it restores on panic as well as on a normal return.
/// Nested guards are correct as long as they are dropped in reverse order of creation,
/// which is what holding them in local variables gives you.  Deliberately dropping them
/// out of order restores an executor that is no longer the displaced one.
///
/// The guard is neither `Send` nor `Sync`: it names a slot belonging to the thread that
/// created it, and dropping it elsewhere would install an executor on the wrong thread.
#[must_use = "the executor is uninstalled as soon as the guard is dropped"]
pub fn install_thread_executor(runtime: Box<DynExecutor>) -> ThreadExecutorGuard {
    ThreadExecutorGuard {
        previous: replace_thread_executor(Some(runtime)),
        _not_send: PhantomData,
    }
}

/// Restores the previous thread executor when dropped.
///
/// Returned by [`install_thread_executor`]; see there for the semantics.
pub struct ThreadExecutorGuard {
    /// What was in the slot before the install, which may be nothing.
    previous: Option<Box<DynExecutor>>,
    /// Ties the guard to the thread that made it; see the note on
    /// [`install_thread_executor`].
    _not_send: PhantomData<*const ()>,
}

impl Drop for ThreadExecutorGuard {
    fn drop(&mut self) {
        replace_thread_executor(self.previous.take());
    }
}

impl Debug for ThreadExecutorGuard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ThreadExecutorGuard")
            .field("previous", &self.previous)
            .finish()
    }
}

/// Accesses the local executor that is available for the current thread.
///
/// This function provides safe access to the thread-local executor for `!Send` futures.
/// Local executors can only execute futures on the current thread and are useful for
/// working with thread-local data or resources that cannot be safely moved between threads.
///
/// If no executor has been set for the thread, the function will panic.
/// You must configure a local executor before spawning local tasks.
///
/// # Parameters
///
/// - `c`: A closure that receives a reference to the thread's local executor.
///   The executor's notifier type is erased to `Box<dyn ExecutorNotified>`.
///
/// # Returns
///
/// Returns whatever value the closure produces.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::{thread_local_executor, set_thread_local_executor};
///
/// # fn example() {
/// thread_local_executor(|exec| {
///     if let Some(executor_rc) = exec {
///         //do something with the local executor
///     }
/// });
/// # }
/// ```
///
/// ## Spawning !Send futures
///
/// ```
/// use some_executor::thread_executor::{thread_local_executor, set_thread_local_executor};
/// use some_executor::SomeLocalExecutor;
/// use some_executor::task::{Task, Configuration};
/// use std::rc::Rc;
/// # use some_executor::observer::Observer;
///
/// # fn example() {
/// // Rc is !Send
/// let shared_data = Rc::new(42);
/// let data_clone = shared_data.clone();
///
/// // Use the thread local executor to spawn a !Send future
/// thread_local_executor(|executor_rc| {
///     if let Some(executor_rc) = executor_rc {
///         let task = Task::without_notifications(
///             "local_task".to_string(),
///             Configuration::default(),
///             async move {
///                 println!("Running !Send future with data: {:?}", data_clone);
///                 42
///             },
///         );
///         let _observer = executor_rc.borrow_mut().spawn_local_objsafe(task.into_objsafe_local());
///     }
/// });
/// # }
/// ```
pub fn thread_local_executor<R>(
    c: impl FnOnce(
        Option<
            Rc<RefCell<Box<dyn SomeLocalExecutor<ExecutorNotifier = Box<dyn ExecutorNotified>>>>>,
        >,
    ) -> R,
) -> R {
    THREAD_LOCAL_EXECUTOR.with(|e| {
        let borrowed = e.borrow();
        match borrowed.as_ref() {
            Some(executor_rc) => {
                let executor_rc = executor_rc.clone();
                drop(borrowed); // Release the borrow before calling the closure
                c(Some(executor_rc))
            }
            None => {
                drop(borrowed); // Release the borrow before calling the closure
                c(None)
            }
        }
    })
}

/// Sets the local executor for the current thread.
///
/// This function associates a local executor with the current thread. Local executors
/// can spawn and execute `!Send` futures, making them suitable for working with
/// thread-local resources.
///
/// # Parameters
///
/// - `runtime`: A boxed local executor with a 'static lifetime and type-erased notifier.
///   The executor must be able to outlive any futures it spawns.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::set_thread_local_executor;
///
/// # fn example() {
/// # let my_local_executor: Box<dyn some_executor::SomeLocalExecutor<'static, ExecutorNotifier = Box<dyn some_executor::observer::ExecutorNotified>>> = todo!();
/// // Set a local executor for the current thread
/// set_thread_local_executor(my_local_executor);
///
/// // Now !Send futures can be spawned on this thread
/// # }
/// ```
///
/// # Lifetime Requirements
///
/// The executor must have a `'static` lifetime, which means it cannot borrow from
/// stack data. This is necessary because the executor may outlive the current
/// stack frame. See the [module documentation](crate::SomeLocalExecutor) for more
/// details on lifetime requirements for local executors.
pub fn set_thread_local_executor(
    runtime: Box<dyn SomeLocalExecutor<'static, ExecutorNotifier = Box<dyn ExecutorNotified>>>,
) {
    THREAD_LOCAL_EXECUTOR.with(|e| {
        let executor_rc = Rc::new(RefCell::new(runtime));
        *e.borrow_mut() = Some(executor_rc);
    });
}
/// Sets the local executor for the current thread with automatic notifier adaptation.
///
/// This is a convenience function that wraps the provided executor in an adapter
/// that erases the specific notifier type to `Box<dyn ExecutorNotified>`. This
/// allows you to use local executors with different notifier types without manually
/// performing the type erasure.
///
/// # Parameters
///
/// - `runtime`: A local executor that implements `SomeLocalExecutor<'static>`. The
///   executor's specific notifier type will be erased.
///
/// # Type Parameters
///
/// - `E`: The concrete type of the local executor. Must implement `SomeLocalExecutor<'static>`
///   and have a `'static` lifetime.
///
/// # Examples
///
/// ```
/// use some_executor::observer::TypedObserver;
/// use some_executor::thread_executor::set_thread_local_executor_adapting_notifier;
///
/// # #[derive(Debug)]
/// # struct MyLocalExecutor;
/// # impl some_executor::SomeLocalExecutor<'static> for MyLocalExecutor {
/// #     type ExecutorNotifier = MyNotifier;
/// #     fn spawn_local<F, N>(&mut self, _: some_executor::task::Task<F, N>) -> impl some_executor::observer::Observer<Value = F::Output>
/// #     where F: std::future::Future + 'static, N: some_executor::observer::ObserverNotified<F::Output>, F::Output: Unpin + 'static
/// #     { todo!() as TypedObserver<F::Output,MyNotifier>}
/// #     fn spawn_local_async<F, N>(&mut self, _: some_executor::task::Task<F, N>) -> impl std::future::Future<Output = impl some_executor::observer::Observer<Value = F::Output>>
/// #     where F: std::future::Future + 'static, N: some_executor::observer::ObserverNotified<F::Output>, F::Output: Unpin + 'static
/// #     { async { todo!() as TypedObserver<F::Output,MyNotifier> } }
/// #     fn spawn_local_objsafe(&mut self, _: some_executor::task::Task<std::pin::Pin<Box<dyn std::future::Future<Output = Box<dyn std::any::Any>>>>, Box<dyn some_executor::observer::ObserverNotified<(dyn std::any::Any + 'static)>>>) -> Box<dyn some_executor::observer::Observer<Value = Box<dyn std::any::Any>, Output = some_executor::observer::FinishedObservation<Box<dyn std::any::Any>>>>
/// #     { todo!() }
/// #     fn spawn_local_objsafe_async<'s>(&'s mut self, _: some_executor::task::Task<std::pin::Pin<Box<dyn std::future::Future<Output = Box<dyn std::any::Any>>>>, Box<dyn some_executor::observer::ObserverNotified<(dyn std::any::Any + 'static)>>>) -> Box<dyn std::future::Future<Output = Box<dyn some_executor::observer::Observer<Value = Box<dyn std::any::Any>, Output = some_executor::observer::FinishedObservation<Box<dyn std::any::Any>>>>> + 's>
/// #     { todo!() }
/// #     fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> { None }
/// # }
/// # struct MyNotifier;
/// # impl some_executor::observer::ExecutorNotified for MyNotifier { fn request_cancel(&mut self) {} }
///
/// // Custom local executor with its own notifier type
/// let my_executor: MyLocalExecutor = MyLocalExecutor;
///
/// // This function handles the notifier type erasure automatically
/// set_thread_local_executor_adapting_notifier(my_executor);
///
/// // The executor is now available with a type-erased notifier
/// ```
///
/// # Implementation Note
///
/// This function uses an internal adapter type to erase the executor's specific
/// notifier type. This allows for a uniform interface while preserving the
/// executor's functionality.
pub fn set_thread_local_executor_adapting_notifier<E: SomeLocalExecutor<'static> + 'static>(
    runtime: E,
) {
    let adapter = crate::local::OwnedSomeLocalExecutorErasingNotifier::new(runtime);
    set_thread_local_executor(Box::new(adapter));
}

/// Accesses the static executor that is available for the current thread.
///
/// This function provides safe access to the thread-static executor. If a user-provided
/// executor has been set via `set_thread_static_executor`, it will be used. Otherwise,
/// the static last resort executor will be used as a fallback, ensuring that a valid
/// executor is always available.
///
/// # Parameters
///
/// - `c`: A closure that receives a reference to the thread's static executor.
///   The closure should return a value of type `R`.
///
/// # Returns
///
/// Returns whatever value the closure produces.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::{thread_static_executor, set_thread_static_executor};
///
/// # fn example() {
/// // Always get a valid static executor (will use last resort if none set)
/// let result = thread_static_executor(|exec| {
///     // exec is always valid - either user-provided or last resort
///     exec.clone_box().executor_notifier().is_some()
/// });
/// println!("Executor notifier available: {}", result);
/// # }
/// ```
///
/// # Panics
///
/// When a user-provided executor is set, its slot is borrowed while the closure
/// runs; calling [`set_thread_static_executor`] from within the closure panics
/// in that case. (When the last-resort fallback is in use, no borrow is held.)
pub fn thread_static_executor<R>(
    c: impl FnOnce(&dyn SomeStaticExecutor<ExecutorNotifier = Box<dyn ExecutorNotified>>) -> R,
) -> R {
    THREAD_STATIC_EXECUTOR.with(|e| {
        let borrowed = e.borrow();
        if let Some(executor) = borrowed.as_ref() {
            c(executor.as_ref())
        } else {
            // Release the borrow before calling the closure: the last-resort
            // executor runs tasks synchronously, and such a task may call
            // set_thread_static_executor (e.g. to bootstrap a real executor),
            // which would otherwise panic on a reentrant borrow.
            drop(borrowed);
            // Use the static last resort executor as fallback
            let last_resort = crate::static_last_resort::StaticLastResortExecutor::new();
            c(&last_resort)
        }
    })
}

/// Sets the static executor for the current thread.
///
/// This function associates a static executor with the current thread. Static executors
/// can spawn `'static` futures that do not need to be `Send`, making them suitable for
/// scenarios where you have static data but need thread-local execution.
///
/// # Parameters
///
/// - `runtime`: A boxed static executor with a type-erased notifier.
///   The executor will be stored in thread-local storage.
///
/// # Note
///
/// Setting a new executor will replace any previously set static executor for this thread.
/// There is no way to "unset" an executor once set; you can only replace it with
/// a different one.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::{set_thread_static_executor, thread_static_executor};
///
/// # fn example() {
/// # let executor: Box<dyn some_executor::SomeStaticExecutor<ExecutorNotifier = Box<dyn some_executor::observer::ExecutorNotified>>> = todo!();
/// // Set a thread-static executor
/// set_thread_static_executor(executor);
///
/// // Verify it can be accessed (will always have a valid executor)
/// thread_static_executor(|exec| {
///     // exec is always valid - either user-provided or last resort
///     let _notifier = exec.clone_box().executor_notifier();
/// });
/// # }
/// ```
pub fn set_thread_static_executor(
    runtime: Box<dyn SomeStaticExecutor<ExecutorNotifier = Box<dyn ExecutorNotified>>>,
) {
    THREAD_STATIC_EXECUTOR.with(|e| {
        *e.borrow_mut() = Some(runtime);
    });
}

/// Sets the static executor for the current thread with automatic notifier adaptation.
///
/// This is a convenience function that wraps the provided executor in an adapter
/// that erases the specific notifier type to `Box<dyn ExecutorNotified>`. This
/// allows you to use static executors with different notifier types without manually
/// performing the type erasure.
///
/// # Parameters
///
/// - `runtime`: A static executor that implements `SomeStaticExecutor`. The
///   executor's specific notifier type will be erased.
///
/// # Type Parameters
///
/// - `E`: The concrete type of the static executor. Must implement `SomeStaticExecutor`
///   and have a `'static` lifetime.
///
/// # Examples
///
/// ```
/// use some_executor::thread_executor::set_thread_static_executor_adapting_notifier;
///
/// # #[derive(Debug)]
/// # struct MyStaticExecutor;
/// # struct MyNotifier;
/// # impl some_executor::observer::ExecutorNotified for MyNotifier { fn request_cancel(&mut self) {} }
/// # impl some_executor::SomeStaticExecutor for MyStaticExecutor {
/// #     type ExecutorNotifier = Box<dyn some_executor::observer::ExecutorNotified>;
/// #     fn spawn_static<F, N>(&mut self, _: some_executor::task::Task<F, N>) -> impl some_executor::observer::Observer<Value = F::Output>
/// #     where F: std::future::Future + 'static, N: some_executor::observer::ObserverNotified<F::Output>, F::Output: Unpin + 'static
/// #     { todo!() as some_executor::observer::TypedObserver<F::Output,Box<dyn some_executor::observer::ExecutorNotified>>}
/// #     fn spawn_static_async<F, N>(&mut self, _: some_executor::task::Task<F, N>) -> impl std::future::Future<Output = impl some_executor::observer::Observer<Value = F::Output>>
/// #     where F: std::future::Future + 'static, N: some_executor::observer::ObserverNotified<F::Output>, F::Output: Unpin + 'static
/// #     { async { todo!() as some_executor::observer::TypedObserver<F::Output,Box<dyn some_executor::observer::ExecutorNotified>> } }
/// #     fn spawn_static_objsafe(&mut self, _: some_executor::ObjSafeStaticTask) -> some_executor::BoxedStaticObserver { todo!() }
/// #     fn spawn_static_objsafe_async<'s>(&'s mut self, _: some_executor::ObjSafeStaticTask) -> some_executor::BoxedStaticObserverFuture<'s> { todo!() }
/// #     fn clone_box(&self) -> Box<some_executor::DynStaticExecutor> { todo!() }
/// #     fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> { None }
/// # }
/// // Use a custom static executor
/// let executor = MyStaticExecutor;
/// set_thread_static_executor_adapting_notifier(executor);
/// ```
///
/// # Implementation Note
///
/// This function uses an internal adapter type to erase the executor's specific
/// notifier type. This allows for a uniform interface while preserving the
/// executor's functionality.
pub fn set_thread_static_executor_adapting_notifier<E: SomeStaticExecutor + 'static>(runtime: E) {
    let adapter = crate::static_support::OwnedSomeStaticExecutorErasingNotifier::new(runtime);
    set_thread_static_executor(Box::new(adapter));
}

/**
Pins a task to run on the current thread; converts non-Send futures to Send futures.

# Discussion

In Rust we prefer Send futures, which allow the executor to move tasks between threads at await
points.  Doing this allows the executor to rebalance the load after futures have begun executing.
For example, the future can resume on the first available thread, rather than the thread it started
on.

This optimization requires that the future is Send, which means that it can't hold a non-Send type
across an await point.  This is a problem for futures that work with non-Send types, such as
Rc or RefCell.

When this is a problem, you can use this function to pin a non-Send task to the current thread.

# Downsides

This is a completely legitimate solution to the problem but it has some downsides:
1.  By nature, a non-Send future cannot be moved around in the thread pool, so it is necessarily
    less efficient than a Send future.
2.  There is some small runtime overhead to handing the Send-to-!Send mismatch.
3.  We go ahead and spawn the task before the return future is polled, which is nonstandard
    in Rust.  However, it is necessary because we must use the current thread to run non-Send tasks.
4.  Cancellation is not supported very well.

Because of these downsides, consider these alternatives to this function:

1.  Consider using Send/Sync types where available.
2.  Consider using a block scope to isolate non-Send types when they don't need to be held across
    await points.  See the example at <https://rust-lang.github.io/async-book/07_workarounds/03_send_approximation.html>.
3.  Consider using the [SomeStaticExecutor] methods directly.  The trouble is the trait itself
    does not require the observer to be Send as not all executors will support it.  But if you know
    the concrete type and it supports this, you can use it directly.

This function primarily comes into play when none of the other alternatives are viable, such as
when Send/Sync types are unavoidable, must be held across await, the executor type is either
erased or does not support Send.

# See also
[Task.pin_current] for a more idiomatic way to pin a task to the current thread.


*/
pub fn pin_static_to_thread<E: SomeStaticExecutor, R, F, N>(
    executor: &mut E,
    task: crate::Task<F, N>,
) -> impl Future<Output = R> + Send + use<E, R, F, N>
where
    F: Future<Output = R> + 'static,
    R: 'static + Send,
    N: crate::observer::ObserverNotified<R> + 'static,
{
    use crate::observer::Observer;
    let (c, fut) = r#continue::continuation();
    //move task into parts
    let label = task.label().to_owned();
    let hint = task.hint();
    let priority = task.priority();
    let poll_after = task.poll_after();
    let configuration = Configuration::new(hint, priority, poll_after);
    //keep the notifier: it must be notified on completion (and dropped without
    //notify on cancellation), the same contract the original task promised.
    let (future, notifier) = task.into_future_and_notifier();
    let t = crate::Task::without_notifications(label.clone(), configuration, async move {
        let r = future.await;
        if let Some(mut n) = notifier {
            crate::observer::ObserverNotified::notify(&mut n, &r);
        }
        c.send(r);
    });
    let o = executor.spawn_static(t);
    let name = format!("pin_static_to_thread continuation for {}", label);
    let t = crate::Task::without_notifications(name, configuration, o);
    executor.spawn_static(t).detach(); //can't hold this across await points

    fut
}

#[cfg(test)]
mod tests {
    use super::{install_thread_executor, thread_executor};
    use crate::current_executor::current_executor;

    /// The case a hand-rolled install cannot handle: there was nothing to put back.
    ///
    /// `set_thread_executor` has no way to express "empty", so before
    /// [`install_thread_executor`] existed an out-of-crate `block_on` override left its
    /// executor installed after returning, and `current_executor()` on that thread
    /// started answering differently than it had before the call.
    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_lite::wasm_lite_test)]
    fn guard_restores_the_empty_slot() {
        assert!(
            thread_executor(|e| e.is_none()),
            "this test needs a thread with no executor to be meaningful"
        );

        {
            let _guard = install_thread_executor(current_executor());
            assert!(thread_executor(|e| e.is_some()));
        }

        assert!(thread_executor(|e| e.is_none()));
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_lite::wasm_lite_test)]
    fn nested_guards_unwind_in_order() {
        let outer = install_thread_executor(current_executor());
        let outer_id = thread_executor(|e| format!("{:?}", e.unwrap()));

        {
            let _inner = install_thread_executor(current_executor());
            assert!(thread_executor(|e| e.is_some()));
        }

        assert_eq!(
            thread_executor(|e| format!("{:?}", e.unwrap())),
            outer_id,
            "dropping the inner guard should restore the outer install, not clear it"
        );
        drop(outer);
        assert!(thread_executor(|e| e.is_none()));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn guard_restores_on_panic() {
        // Its own thread: the slot is process-wide per-thread, and the other tests here
        // assert on an empty one.
        std::thread::spawn(|| {
            let result = std::panic::catch_unwind(|| {
                let _guard = install_thread_executor(current_executor());
                panic!("boom");
            });
            assert!(result.is_err());
            assert!(thread_executor(|e| e.is_none()));
        })
        .join()
        .expect("thread panicked");
    }
}