some_executor 0.4.1

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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
//SPDX-License-Identifier: MIT OR Apache-2.0

use std::any::Any;
use std::cell::RefCell;
use std::convert::Infallible;
use std::fmt::{Debug, Formatter};
use std::future::{Future};
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::task::{Context, Poll};
use crate::hint::Hint;
use crate::observer::{observer_channel, ExecutorNotified, TypedObserver, ObserverNotified, ObserverSender};
use crate::{task_local, DynExecutor, SomeLocalExecutor, Priority, SomeExecutor};
use crate::dyn_observer_notified::ObserverNotifiedErased;
use crate::local::UnsafeErasedLocalExecutor;

/**
A task identifier.

This is a unique identifier for a task.
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TaskID(u64);

impl TaskID {
    /**
    Creates a task ID from an opaque u64.

    The only valid value comes from a previous call to [TaskID::to_u64].
    */
    pub fn from_u64(id: u64) -> Self {
        TaskID(id)
    }

    /**
    Converts the task ID to an opaque u64.

    The only valid use of this value is to pass it to [TaskID::from_u64].
    */
    pub fn to_u64(self) -> u64 {
        self.0
    }
}

impl<F: Future, N> From<&Task<F, N>> for TaskID {
    fn from(task: &Task<F, N>) -> Self {
        task.task_id()
    }
}


static TASK_IDS: AtomicU64 = AtomicU64::new(0);


/**
A top-level future.

The Task contains information that can be useful to an executor when deciding how to run the future.
*/
#[derive(Debug)]
#[must_use]
pub struct Task<F, N>
where
    F: Future,
{
    future: F,
    hint: Hint,
    label: String,
    poll_after: crate::sys::Instant,
    notifier: Option<N>,
    priority: Priority,
    task_id: TaskID,
}

/**
A task suitable for spawning.

Executors convert [Task] into this type in order to poll the future.
*/
pub struct SpawnedTask<F, ONotifier, Executor>
where
    F: Future,
{
    task: F,
    sender: ObserverSender<F::Output, ONotifier>,
    phantom: PhantomData<Executor>,
    poll_after: crate::sys::Instant,
    hint: Hint,
    //these task_local properties optional so we can take/replace them
    label: Option<String>,
    cancellation: Option<InFlightTaskCancellation>,
    executor: Option<Box<dyn SomeExecutor<ExecutorNotifier=Infallible>>>,
    priority: Priority, //copy,so no need to repair/replace them, boring
    task_id: TaskID, //boring
}

/**
A task suitable for spawning.

Executors convert [Task] into this type in order to poll the future.

# Design note

[SpawnedTask] has an embedded copy of the executor. This is fine for that type, since shared executors
necessarily involve some nice owned type, like a channel or `Arc<Mutex>`.

[SomeLocalExecutor] is quite different, and may be implemented as a reference to a local executor.  A few issues
with this, the big one is that we want to spawn with `&mut Executor`, but if tasks embed some kind of &Executor,
we can't do that.

Instead what we need to do is inject the executor on each poll, which means that the task itself cannot be a future.

*/
pub struct SpawnedLocalTask<F, ONotifier, Executor>
where
    F: Future,
{
    task: F,
    sender: ObserverSender<F::Output, ONotifier>,
    poll_after: crate::sys::Instant,
    executor: PhantomData<Executor>,
    //these task-local properties are optional so we can move them in and out
    label: Option<String>,
    cancellation: Option<InFlightTaskCancellation>,
    //copy-safe task-local properties
    hint: Hint,
    priority: Priority,
    task_id: TaskID,
}


impl<F: Future, ONotifier, ENotifier> SpawnedTask<F, ONotifier, ENotifier> {
    pub fn hint(&self) -> Hint {
        self.hint
    }

    pub fn label(&self) -> &str {
        self.label.as_ref().expect("Future is polling")
    }

    pub fn priority(&self) -> priority::Priority {
        self.priority
    }

    // pub(crate) fn task_cancellation(&self) -> InFlightTaskCancellation {
    //     self.task.get_future().get_future().get_val(|cancellation| cancellation.clone())
    // }

    pub fn poll_after(&self) -> crate::sys::Instant {
        self.poll_after
    }

    pub fn task_id(&self) -> TaskID {
        self.task_id
    }

    pub fn into_future(self) -> F {
        self.task
    }
}

impl<'executor, F: Future, ONotifier, Executor> SpawnedLocalTask<F, ONotifier, Executor> {
    pub fn hint(&self) -> Hint {
        self.hint
    }

    pub fn label(&self) -> &str {
        self.label.as_ref().expect("Future is polling")
    }

    pub fn priority(&self) -> priority::Priority {
        self.priority
    }

    // pub(crate) fn task_cancellation(&self) -> InFlightTaskCancellation {
    //     self.task.get_future().get_future().get_val(|cancellation| cancellation.clone())
    // }

    pub fn poll_after(&self) -> crate::sys::Instant {
        self.poll_after
    }

    pub fn task_id(&self) -> TaskID {
        self.task_id
    }

    pub fn into_future(self) -> F {
        self.task
    }
}
/**
Provides information about the cancellation status of the current task.
*/
#[derive(Debug)]
pub struct InFlightTaskCancellation(Arc<AtomicBool>);

impl InFlightTaskCancellation {
    //we don't publish this so that we can change implementation later
    pub(crate) fn clone(&self) -> Self {
        InFlightTaskCancellation(self.0.clone())
    }

    pub(crate) fn cancel(&self) {
        self.0.store(true, std::sync::atomic::Ordering::Relaxed);
    }

    /**
    Returns true if the task has been cancelled.

    Code inside the task may wish to check this and return early.

    It is not required that anyone check this value.
    */
    pub fn is_cancelled(&self) -> bool {
        self.0.load(std::sync::atomic::Ordering::Relaxed)
    }
}


task_local! {
    /**
    Provides a debugging label to identify the current task.
    */
    pub static const TASK_LABEL: String;
    /**
    Provides a priority for the current task.
     */
    pub static const TASK_PRIORITY: priority::Priority;
    /**
    Provides a mechanism for tasks to determine if they have been cancelled.

    Tasks can use this to determine if they should stop running.
    */
    pub static const IS_CANCELLED: InFlightTaskCancellation;

    /**
    Provides a unique identifier for the current task.
     */
    pub static const TASK_ID: TaskID;

    /**
    Provides an executor local to the current task.
    */
    pub static const TASK_EXECUTOR: Option<Box<DynExecutor>>;
}

thread_local! {
    pub static TASK_LOCAL_EXECUTOR: RefCell<Option<Box<dyn SomeLocalExecutor<'static, ExecutorNotifier=Box<dyn ExecutorNotified>>>>> = RefCell::new(None);
}

impl<F: Future, N> Task<F, N> {
    /**
    Creates a new task.

    # Parameters
    - `label`: A human-readable label for the task.
    - `future`: The future to run.
    - `configuration`: Configuration for the task.
    - `notifier`: An observer to notify when the task completes.  If there is no notifier, consider using [Self::without_notifications] instead.
    */
    pub fn with_notifications(label: String, future: F, configuration: Configuration, notifier: Option<N>) -> Self
    where
        F: Future,
    {
        let task_id = TaskID(TASK_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));

        assert_ne!(task_id.0, u64::MAX, "TaskID overflow");
        Task {
            label,
            future,
            hint: configuration.hint,
            poll_after: configuration.poll_after,
            priority: configuration.priority,
            notifier,
            task_id,
        }
    }

    pub fn hint(&self) -> Hint {
        self.hint
    }

    pub fn label(&self) -> &str {
        self.label.as_ref()
    }

    pub fn priority(&self) -> priority::Priority {
        self.priority
    }


    /**
    The time after which the task should be polled.

    Executors must not poll the task before this time.  An executor may choose to implement this in a variety of
    ways, such as using a timer, sleeping the thread, etc.
    */
    pub fn poll_after(&self) -> crate::sys::Instant {
        self.poll_after
    }

    pub fn task_id(&self) -> TaskID {
        self.task_id
    }

    pub fn into_future(self) -> F {
        self.future
    }

    /**
    Spawns the task onto the executor.

    When using this method, the TASK_LOCAL_EXECUTOR will be set to None.
    To spawn a task onto a local executor instead, use [Task::spawn_local].
    */
    pub fn spawn<Executor: SomeExecutor>(mut self, executor: &mut Executor) -> (SpawnedTask<F, N, Executor>, TypedObserver<F::Output, Executor::ExecutorNotifier>) {
        let cancellation = InFlightTaskCancellation::default();
        let some_notifier: Option<Executor::ExecutorNotifier> = executor.executor_notifier();
        let task_id = self.task_id();
        let (sender, receiver) = observer_channel(self.notifier.take(), some_notifier, cancellation.clone(), task_id);
        let boxed_executor = executor.clone_box();
        let spawned_task = SpawnedTask {
            task: self.future,
            sender,
            phantom: PhantomData,
            poll_after: self.poll_after,
            hint: self.hint,
            label: Some(self.label),
            priority: self.priority,
            task_id,
            cancellation: Some(cancellation),
            executor: Some(boxed_executor),
        };
        (spawned_task, receiver)
    }

    /**
    Spawns the task onto a local executor
    */
    pub fn spawn_local<'executor, Executor: SomeLocalExecutor<'executor>>(mut self, executor: &mut Executor) -> (SpawnedLocalTask<F, N, Executor>, TypedObserver<F::Output, Executor::ExecutorNotifier>) {
        let cancellation = InFlightTaskCancellation::default();
        let task_id = self.task_id();
        let (sender, receiver) = observer_channel(self.notifier.take(), executor.executor_notifier(), cancellation.clone(), task_id);
        let spawned_task = SpawnedLocalTask {
            task: self.future,
            sender,
            executor: PhantomData,
            poll_after: self.poll_after,
            hint: self.hint,
            priority: self.priority,
            label: Some(self.label),
            task_id,
            cancellation: Some(cancellation),
        };
        (spawned_task, receiver)
    }
    /**
    Spawns the task onto a local executor.

    # Objsafe

    A word on exactly what 'objsafe' means in this context.  Objsafe means that whoever is spawning the task,
    doesn't know which executor they are using, so they spawn onto an objsafe executor via the objsafe methods.

    This has two implications.  First, we need to hide the executor type from the spawner.  However, we don't need
    to hide it from the *executor*, since the executor knows what it is.  Accordingly, this information is erased
    with respect to types sent to the spawner, and not erased with respect to types sent
    to the executor.

    Second, the objsafe spawn method cannot have any generics.  Therefore, the future type is erased (boxed) and worse,
    the output type is erased as well.  Accordingly we do not know what it is.
    */

    pub fn spawn_objsafe<Executor: SomeExecutor>(mut self, executor: &mut Executor) -> (SpawnedTask<F, N, Executor>, TypedObserver<F::Output, Box<dyn ExecutorNotified + Send>>) {
        let cancellation = InFlightTaskCancellation::default();
        let boxed_executor_notifier = executor.executor_notifier().map(|n| Box::new(n) as Box<dyn ExecutorNotified + Send>);
        let boxed_executor = executor.clone_box();
        let (sender, receiver) = observer_channel(self.notifier.take(), boxed_executor_notifier, cancellation.clone(), self.task_id);
        let spawned_task = SpawnedTask {
            task: self.future,
            sender,
            phantom: PhantomData,
            poll_after: self.poll_after,
            hint: self.hint,
            label: Some(self.label),
            priority: self.priority,
            task_id: self.task_id,
            cancellation: Some(cancellation),
            executor: Some(boxed_executor),
        };
        (spawned_task, receiver)
    }

    /**
    Spawns the task onto a local executor.

    # Objsafe

    A word on exactly what 'objsafe' means in this context.  Objsafe means that whoever is spawning the task,
    doesn't know which executor they are using, so they spawn onto an objsafe executor via the objsafe methods.

    This has two implications.  First, we need to hide the executor type from the spawner.  However, we don't need
    to hide it from the *executor*, since the executor knows what it is.  Accordingly this information is erased
    with respect to types sent to the spawner, and not erased with respect to types sent
    to the executor.

    Second, the objsafe spawn method cannot have any generics.  Therefore, the future type is erased (boxed) and worse,
    the output type is erased as well.  Accordingly we do not know what it is.
    */
    pub fn spawn_local_objsafe<'executor, Executor: SomeLocalExecutor<'executor>>(mut self, executor: &mut Executor) -> (SpawnedLocalTask<F, N, Executor>, TypedObserver<F::Output, Box<dyn ExecutorNotified>>) {
        let cancellation = InFlightTaskCancellation::default();
        let task_id = self.task_id();

        let boxed_executor_notifier = executor.executor_notifier().map(|n| Box::new(n) as Box<dyn ExecutorNotified>);
        let (sender, receiver) = observer_channel(self.notifier.take(), boxed_executor_notifier, cancellation.clone(), task_id);
        let spawned_task = SpawnedLocalTask {
            task: self.future,
            sender,
            poll_after: self.poll_after,
            hint: self.hint,
            priority: self.priority,
            executor: PhantomData,
            label: Some(self.label),
            task_id,
            cancellation: Some(cancellation),
        };
        (spawned_task, receiver)
    }

    /**
    Converts this task into one suitable for spawn_objsafe
    */
    pub fn into_objsafe(self) -> Task<Pin<Box<dyn Future<Output=Box<dyn Any + 'static + Send>> + 'static + Send>>, Box<dyn ObserverNotified<dyn Any + Send> + Send>>
    where N: ObserverNotified<F::Output> + Send,
    F::Output: Send + 'static + Unpin,
    F: Send + 'static {
        let notifier = self.notifier.map(|n| Box::new(ObserverNotifiedErased::new(n)) as Box<dyn ObserverNotified<dyn Any + Send> + Send>);
        Task::new_objsafe(self.label, Box::new(
            async move {
                Box::new(self.future.await) as Box<dyn Any + Send + 'static>
            }
        ), Configuration::new(self.hint, self.priority, self.poll_after), notifier)
    }
}

//infalliable notification methods

impl<F: Future> Task<F, Infallible> {
    /**
    Spawns a task, without performing inline notification.

    Use this constructor when there are no cancellation notifications desired.

    # Parameters
    - `label`: A human-readable label for the task.
    - `future`: The future to run.
    - `configuration`: Configuration for the task.

    # Details

    Use of this function is equivalent to calling [Task::with_notifications] with a None notifier.

    This function avoids the need to specify the type parameter to [Task].
    */
    pub fn without_notifications(label: String, future: F, configuration: Configuration) -> Self {
        Task::with_notifications(label, future, configuration, None)
    }
}

fn common_poll<'l, F, N, L>(future: Pin<&mut F>, sender: &mut ObserverSender<F::Output, N>, label: &mut Option<String>, cancellation: &mut Option<InFlightTaskCancellation>,
                            executor: &mut Option<Box<dyn SomeExecutor<ExecutorNotifier=Infallible>>>,
                            local_executor: Option<&mut L>,
                            priority: Priority, task_id: TaskID, poll_after: crate::sys::Instant, cx: &mut Context) -> std::task::Poll<()>
where
    F: Future,
    N: ObserverNotified<F::Output>,
    L: SomeLocalExecutor<'l> ,
{
    assert!(poll_after <= crate::sys::Instant::now(), "Conforming executors should not poll tasks before the poll_after time.");
    if sender.observer_cancelled() {
        //we don't really need to notify the observer here.  Also the notifier will run upon drop.
        return Poll::Ready(());
    }
    //before poll, we need to set our properties
    unsafe {
        TASK_LABEL.with_mut(|l| {
            *l = Some(label.take().expect("Label not set (is task being polled already?)"));
        });
        IS_CANCELLED.with_mut(|c| {
            *c = Some(cancellation.take().expect("Cancellation not set (is task being polled already?)"));
        });
        TASK_PRIORITY.with_mut(|p| {
            *p = Some(priority);
        });
        TASK_ID.with_mut(|i| {
            *i = Some(task_id);
        });
        TASK_EXECUTOR.with_mut(|e| {
            *e = Some(executor.take());
        });
        if let Some(local_executor) = local_executor {
            let mut erased_value_executor = Box::new(crate::local::SomeLocalExecutorErasingNotifier::new(local_executor)) as Box<dyn SomeLocalExecutor<ExecutorNotifier=Box<dyn ExecutorNotified>> + '_>;
            let erased_value_executor_ref = Box::as_mut(&mut erased_value_executor);
            let erased_unsafe_executor = UnsafeErasedLocalExecutor::new(erased_value_executor_ref);
            TASK_LOCAL_EXECUTOR.with(|e| {
                e.borrow_mut().replace(Box::new(erased_unsafe_executor));
            });
        }
    }
    let r = future.poll(cx);
    //after poll, we need to set our properties
    unsafe {
        TASK_LABEL.with_mut(|l| {
            let read_label = l.take().expect("Label not set");
            *label = Some(read_label);
        });
        IS_CANCELLED.with_mut(|c| {
            let read_cancellation = c.take().expect("Cancellation not set");
            *cancellation = Some(read_cancellation);
        });
        TASK_PRIORITY.with_mut(|p| {
            *p = None;
        });
        TASK_ID.with_mut(|i| {
            *i = None;
        });
        TASK_EXECUTOR.with_mut(|e| {
            let read_executor = e.take().expect("Executor not set");
            *executor = read_executor
        });
        TASK_LOCAL_EXECUTOR.with_borrow_mut(|e| {
            *e = None;
        });
    }
    match r {
        Poll::Ready(r) => {
            sender.send(r);
            Poll::Ready(())
        }
        Poll::Pending => {
            Poll::Pending
        }
    }
}

impl<F: Future, ONotifier, E> SpawnedTask<F, ONotifier, E>
where ONotifier: ObserverNotified<F::Output> {
    /**
    Polls the task.  This has the standard semantics for Rust futures.

    # Parameters
    - `cx`: The context for the poll.
    - `local_executor`: A local executor, if available.  This will be used to populate the thread-local [TASK_LOCAL_EXECUTOR] variable.
    */
    fn poll<'l, L>(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, local_executor: Option<&mut L>) -> std::task::Poll<()> where
        L: SomeLocalExecutor<'l>
    {
        //destructure
        let poll_after = self.poll_after();
        let (future, sender, label, priority,
            cancellation, task_id, executor) = unsafe {
            let unchecked = self.get_unchecked_mut();
            let future = Pin::new_unchecked(&mut unchecked.task);
            let sender = Pin::new_unchecked(&mut unchecked.sender);
            let label = Pin::new_unchecked(&mut unchecked.label);
            let priority = Pin::new_unchecked(&mut unchecked.priority);
            let cancellation = Pin::new_unchecked(&mut unchecked.cancellation);
            let task_id = unchecked.task_id;
            let executor = Pin::new_unchecked(&mut unchecked.executor);
            (future, sender, label, priority, cancellation, task_id, executor)
        };

        common_poll(future, sender.get_mut(), label.get_mut(), cancellation.get_mut(), executor.get_mut(), local_executor, *priority.get_mut(), task_id, poll_after, cx)
    }
}

impl<F, ONotifier, E> Future for SpawnedTask<F, ONotifier, E>
    where
        F: Future,
        ONotifier: ObserverNotified<F::Output>,
    {
        type Output = ();
        /**
        Implements Future trait by declining to set a local context.
    */
        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            SpawnedTask::poll::<Infallible>(self, cx, None)
        }
    }

    impl<'executor, F, ONotifier, Executor: SomeLocalExecutor<'executor>> SpawnedLocalTask<F, ONotifier, Executor>
    where
        F: Future,
        ONotifier: ObserverNotified<F::Output>,
    {
        //I can't believe it's not future

        /**
        Polls the task.  This has the standard semantics for Rust futures.

        # Parameters
        - `cx`: The context for the poll.
        - `executor`: The executor the task was spawned on.  This will be used to populate the thread-local [TASK_LOCAL_EXECUTOR] variable.
        - `some_executor`: An executor for spawning new tasks, if desired.  This is used to populate the task-local [TASK_EXECUTOR] variable.
        */
        pub fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, executor: &mut Executor,
                    mut some_executor: Option<Box<(dyn SomeExecutor<ExecutorNotifier=Infallible> + 'static)>>) -> std::task::Poll<()> {
            let poll_after = self.poll_after();
            //destructure
            let (future, sender, label, priority,
                cancellation, task_id) = unsafe {
                let unchecked = self.get_unchecked_mut();
                let future = Pin::new_unchecked(&mut unchecked.task);
                let sender = Pin::new_unchecked(&mut unchecked.sender);
                let label = Pin::new_unchecked(&mut unchecked.label);
                let priority = Pin::new_unchecked(&mut unchecked.priority);
                let cancellation = Pin::new_unchecked(&mut unchecked.cancellation);
                let task_id = unchecked.task_id;
                (future, sender, label, priority, cancellation, task_id)
            };

            common_poll(future, sender.get_mut(), label.get_mut(), cancellation.get_mut(), &mut some_executor, Some(executor), *priority.get_mut(), task_id, poll_after, cx)
        }
    }

    impl Task<Pin<Box<dyn Future<Output=Box<dyn Any + Send + 'static>> + Send + 'static>>, Box<dyn ObserverNotified<dyn Any + Send> + Send>> {
        /**
        Creates a new objsafe future
*/
        pub fn new_objsafe(label: String, future: Box<dyn Future<Output=Box<dyn Any + Send + 'static>> + Send + 'static>, configuration: Configuration, notifier: Option<Box<dyn ObserverNotified<dyn Any + Send> + Send>>) -> Self {
            Self::with_notifications(label, Box::into_pin(future), configuration, notifier)
        }
    }


    /**
    Information needed to spawn a task.
    */
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub struct Configuration {
        hint: Hint,
        priority: priority::Priority,
        poll_after: crate::sys::Instant,
    }

    /**
    A builder for [Configuration].
    */
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
    pub struct ConfigurationBuilder {
        hint: Option<Hint>,
        priority: Option<Priority>,
        poll_after: Option<crate::sys::Instant>,
    }

    impl ConfigurationBuilder {
        pub fn new() -> Self {
            ConfigurationBuilder {
                hint: None,
                priority: None,
                poll_after: None,
            }
        }

        /**
        Provide a hint about the runtime characteristics of the future.
        */

        pub fn hint(mut self, hint: Hint) -> Self {
            self.hint = Some(hint);
            self
        }

        /**
        Provide a priority for the future.

        See the [Priority] type for details.
        */
        pub fn priority(mut self, priority: priority::Priority) -> Self {
            self.priority = Some(priority);
            self
        }

        /**
        Provide a time after which the future should be polled.
        */
        pub fn poll_after(mut self, poll_after: crate::sys::Instant) -> Self {
            self.poll_after = Some(poll_after);
            self
        }

        pub fn build(self) -> Configuration {
            Configuration {
                hint: self.hint.unwrap_or_else(|| Hint::default()),
                priority: self.priority.unwrap_or_else(|| priority::Priority::Unknown),
                poll_after: self.poll_after.unwrap_or_else(|| crate::sys::Instant::now()),
            }
        }
    }

    impl Configuration {
        pub fn new(hint: Hint, priority: priority::Priority, poll_after: crate::sys::Instant) -> Self {
            Configuration {
                hint,
                priority,
                poll_after,
            }
        }
    }

    /**
    ObjSafe type-erased wrapper for [SpawnedLocalTask].
    */
    pub trait DynLocalSpawnedTask<Executor> {
        fn poll<'executor>(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, executor: &'executor mut Executor, some_executor: Option<Box<(dyn SomeExecutor<ExecutorNotifier=Infallible> + 'static)>>) -> std::task::Poll<()>;
        fn poll_after(&self) -> crate::sys::Instant;
        fn label(&self) -> &str;

        fn task_id(&self) -> TaskID;

        fn hint(&self) -> Hint;
        fn priority(&self) -> priority::Priority;
    }

    impl<'executor, F, ONotifier, Executor> DynLocalSpawnedTask<Executor> for SpawnedLocalTask<F, ONotifier, Executor>
    where
        F: Future,
        Executor: SomeLocalExecutor<'executor>,
        ONotifier: ObserverNotified<F::Output>,
    {
        fn poll<'ex>(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, executor: &'ex mut Executor, some_executor: Option<Box<(dyn SomeExecutor<ExecutorNotifier=Infallible> + 'static)>>) -> std::task::Poll<()> {
            SpawnedLocalTask::poll(self, cx, executor, some_executor)
        }

        fn poll_after(&self) -> crate::sys::Instant {
            self.poll_after
        }
        fn label(&self) -> &str {
            self.label()
        }

        fn hint(&self) -> Hint {
            self.hint
        }
        fn priority(&self) -> priority::Priority {
            self.priority()
        }

        fn task_id(&self) -> TaskID {
            self.task_id()
        }
    }

    /**
    ObjSafe type-erased wrapper for [SpawnedTask].

    If you have no relevant type parameter, choose [Infallible].
    */
    pub trait DynSpawnedTask<LocalExecutorType>: Send + Debug {
        fn poll<'l>(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, local_executor: Option<&mut LocalExecutorType>) -> std::task::Poll<()>
        where LocalExecutorType: SomeLocalExecutor<'l>;

        fn poll_after(&self) -> crate::sys::Instant;
        fn label(&self) -> &str;

        fn task_id(&self) -> TaskID;

        fn hint(&self) -> Hint;
        fn priority(&self) -> priority::Priority;
    }


    impl<F: Future, N: ObserverNotified<<F as Future>::Output>, E,L> DynSpawnedTask<L> for SpawnedTask<F, N, E>
    where F: Send, E: Send, N: Send, F::Output: Send{
        fn poll<'l>(self: Pin<&mut Self>, cx: &mut Context<'_>, local_executor: Option<&mut L>) -> Poll<()>
        where
            L: SomeLocalExecutor<'l>,
        {
            SpawnedTask::poll(self, cx, local_executor)

        }

        fn poll_after(&self) -> crate::sys::Instant {
            self.poll_after()
        }

        fn label(&self) -> &str {
            self.label()
        }

        fn task_id(&self) -> TaskID {
            self.task_id()
        }

        fn hint(&self) -> Hint {
            self.hint()
        }

        fn priority(&self) -> priority::Priority {
            self.priority()
        }
    }

    /* boilerplates

    configuration - default

    */
    impl Default for Configuration {
        fn default() -> Self {
            Configuration {
                hint: Hint::default(),
                priority: priority::Priority::Unknown,
                poll_after: crate::sys::Instant::now(),
            }
        }
    }

    /*
    I don't think it makes sense to support Clone on Task.
    That eliminates the need for PartialEq, Eq, Hash.  We have ID type for this.

    I suppose we could implement Default with a blank task...

     */

    /**
    A future that always returns Ready(()).
    */
    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
    pub struct DefaultFuture;
    impl Future for DefaultFuture {
        type Output = ();
        fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
            Poll::Ready(())
        }
    }
    impl Default for Task<DefaultFuture, Infallible> {
        fn default() -> Self {
            Task::with_notifications("".to_string(), DefaultFuture, Configuration::default(), None)
        }
    }

impl<F: Future,N,E> Debug for SpawnedTask<F,N,E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpawnedTask")
            .field("poll_after", &self.poll_after)
            .field("hint", &self.hint)
            .field("label", &self.label)
            .field("priority", &self.priority)
            .field("task_id", &self.task_id)
            .finish()
    }
}

impl<F: Future,N,E> Debug for SpawnedLocalTask<F,N,E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpawnedLocalTask")
            .field("poll_after", &self.poll_after)
            .field("hint", &self.hint)
            .field("label", &self.label)
            .field("priority", &self.priority)
            .field("task_id", &self.task_id)
            .finish()
    }
}

    /*
    Support from for the Future type
     */

    impl<F: Future, N> From<F> for Task<F, N> {
        fn from(future: F) -> Self {
            Task::with_notifications("".to_string(), future, Configuration::default(), None)
        }
    }

    /*
    Support AsRef for the underlying future type
     */

    impl<F: Future, N> AsRef<F> for Task<F, N> {
        fn as_ref(&self) -> &F {
            &self.future
        }
    }

    /*
    Support AsMut for the underlying future type
     */
    impl<F: Future, N> AsMut<F> for Task<F, N> {
        fn as_mut(&mut self) -> &mut F {
            &mut self.future
        }
    }

    /*
    Analogously, for spawned task...
     */

    impl<F: Future, N, E> AsRef<F> for SpawnedTask<F, N, E> {
        fn as_ref(&self) -> &F {
            &self.task
        }
    }

    impl<F: Future, N, E> AsMut<F> for SpawnedTask<F, N, E> {
        fn as_mut(&mut self) -> &mut F {
            &mut self.task
        }
    }

    impl<F: Future, N, E> AsRef<F> for SpawnedLocalTask<F, N, E> {
        fn as_ref(&self) -> &F {
            &self.task
        }
    }

    impl<F: Future, N, E> AsMut<F> for SpawnedLocalTask<F, N, E> {
        fn as_mut(&mut self) -> &mut F {
            &mut self.task
        }
    }

    /*
    InFlightTaskCancellation
    - don't want to publish clone right now.  Eliminates Copy,Eq,Hash, etc.

    Default is possible I suppose
     */

    impl Default for InFlightTaskCancellation {
        fn default() -> Self {
            InFlightTaskCancellation(Arc::new(AtomicBool::new(false)))
        }
    }

    impl From<bool> for InFlightTaskCancellation {
        fn from(value: bool) -> Self {
            InFlightTaskCancellation(Arc::new(AtomicBool::new(value)))
        }
    }

    impl Into<bool> for InFlightTaskCancellation {
        fn into(self) -> bool {
            self.0.load(std::sync::atomic::Ordering::Relaxed)
        }
    }

    //taskID.  I think we want to support various conversions to and from u64

    impl From<u64> for TaskID {
        /**
        Equivalent to [TaskID::from_u64].
        */
        fn from(id: u64) -> Self {
            TaskID::from_u64(id)
        }
    }

    impl From<TaskID> for u64 {
        /**
        Equivalent to [TaskID::to_u64].
        */

        fn from(id: TaskID) -> u64 {
            id.to_u64()
        }
    }

    impl AsRef<u64> for TaskID {
        /**
        Equivalent to [TaskID::to_u64].
        */
        fn as_ref(&self) -> &u64 {
            &self.0
        }
    }

/*dyn traits boilerplate

Don't want to implement eq, etc. at this time –use task ID.

AsRef / sure, why not
 */

impl<'a, F,N,E> AsRef<dyn DynSpawnedTask<Infallible> + 'a> for SpawnedTask<F,N,E>
where N: ObserverNotified<F::Output>,
    F: Future + 'a,
F: Send,
N: Send,
E: Send + 'a,
F::Output: Send,{
    fn as_ref(&self) -> &(dyn DynSpawnedTask<Infallible> + 'a) {
        self
    }
}

impl<'a, F,N,E> AsMut<dyn DynSpawnedTask<Infallible> + 'a> for SpawnedTask<F,N,E>
where N: ObserverNotified<F::Output>,
      F: Future + 'a,
      F: Send,
      N: Send,
      E: Send + 'a,
      F::Output: Send,{
    fn as_mut(&mut self) -> &mut (dyn DynSpawnedTask<Infallible> + 'a) {
        self
    }
}



    #[cfg(test)]
    mod tests {
        use std::any::Any;
        use std::convert::Infallible;
        use std::future::Future;
        use std::pin::Pin;
        use crate::observer::{ObserverNotified, Observer, FinishedObservation};
        use crate::task::{DynLocalSpawnedTask, DynSpawnedTask, SpawnedTask, Task};
        use crate::{task_local, SomeExecutor, SomeLocalExecutor};

        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_create_task() {
            let task: Task<_, Infallible> = Task::with_notifications("test".to_string(), async {}, Default::default(), None);
            assert_eq!(task.label(), "test");
        }

        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_create_no_notify() {
            let t = Task::without_notifications("test".to_string(), async {}, Default::default());
            assert_eq!(t.label(), "test");
        }
        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_send() {
            task_local!(
            static FOO: u32;
        );

            let scoped = FOO.scope(42, async {});

            fn assert_send<T: Send>(_: T) {}
            assert_send(scoped);
        }

        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_dyntask_objsafe() {
            let _d: &dyn DynSpawnedTask<Infallible>;
        }

        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_send_task() {
            #[allow(unused)]
            fn task_check<F: Future + Send, N: Send>(task: Task<F, N>) {
                fn assert_send<T: Send>(_: T) {}
                assert_send(task);
            }
            #[allow(unused)]
            fn task_check_sync<F: Future + Sync, N: Sync>(task: Task<F, N>) {
                fn assert_sync<T: Sync>(_: T) {}
                assert_sync(task);
            }
            #[allow(unused)]
            fn task_check_unpin<F: Future + Unpin, N: Unpin>(task: Task<F, N>) {
                fn assert_unpin<T: Unpin>(_: T) {}
                assert_unpin(task);
            }

            #[allow(unused)]
            fn spawn_check<F: Future + Send, E: SomeExecutor>(task: Task<F, Infallible>, exec: &mut E)
            where
                F::Output: Send,
                E: Send,
            {
                let spawned: SpawnedTask<F, Infallible, E> = task.spawn(exec).0;
                fn assert_send<T: Send>(_: T) {}
                assert_send(spawned);
            }

            #[allow(unused)]
            fn spawn_check_sync<F: Future + Sync, E: SomeExecutor>(task: Task<F, Infallible>, exec: &mut E)
            where
                F::Output: Send,
                E::ExecutorNotifier: Sync,
            {
                let spawned: SpawnedTask<F, Infallible, E> = task.spawn(exec).0;
                fn assert_sync<T: Sync>(_: T) {}
                assert_sync(spawned);
            }

            #[allow(unused)]
            fn spawn_check_unpin<F: Future + Unpin, E: SomeExecutor>(task: Task<F, Infallible>, exec: &mut E)
            where
                E: Unpin,
            {
                let spawned: SpawnedTask<F, Infallible, E> = task.spawn(exec).0;
                fn assert_unpin<T: Unpin>(_: T) {}
                assert_unpin(spawned);
            }
        }


        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        fn test_local_executor() {
            struct ExLocalExecutor<'future>(Vec<Pin<Box<dyn DynLocalSpawnedTask<ExLocalExecutor<'future>> + 'future>>>);

            impl<'existing_tasks, 'new_task> SomeLocalExecutor<'new_task> for ExLocalExecutor<'existing_tasks>
            where
                'new_task: 'existing_tasks,
            {
                type ExecutorNotifier = Infallible;

                fn spawn_local<F: Future, Notifier: ObserverNotified<F::Output>>(&mut self, task: Task<F, Notifier>) -> impl Observer<Value=F::Output>
                where
                    Self: Sized,
                    F: 'new_task,
                    F::Output: 'static,
                /* I am a little uncertain whether this is really required */
                    <F as Future>::Output: Unpin,
                {
                    let (spawn, observer) = task.spawn_local(self);
                    let pinned_spawn = Box::pin(spawn);
                    self.0.push(pinned_spawn);
                    observer
                }

                fn spawn_local_async<F: Future, Notifier: ObserverNotified<F::Output>>(&mut self, task: Task<F, Notifier>) -> impl Future<Output=impl Observer<Value=F::Output>>
                where
                    Self: Sized,
                    F: 'new_task,
                    F::Output: 'static
                {
                    async {
                        let (spawn, observer) = task.spawn_local(self);
                        let pinned_spawn = Box::pin(spawn);
                        self.0.push(pinned_spawn);
                        observer
                    }
                }

                fn spawn_local_objsafe(&mut self, task: Task<Pin<Box<dyn Future<Output=Box<dyn Any>>>>, Box<dyn ObserverNotified<(dyn Any + 'static)>>>) -> Box<dyn Observer<Value=Box<dyn Any>, Output = FinishedObservation<Box<dyn Any>>>> {
                    let (spawn, observer) = task.spawn_local_objsafe(self);
                    let pinned_spawn = Box::pin(spawn);
                    self.0.push(pinned_spawn);
                    Box::new(observer)
                }

                fn spawn_local_objsafe_async<'s>(&'s mut self, task: Task<Pin<Box<dyn Future<Output=Box<dyn Any>>>>, Box<dyn ObserverNotified<(dyn Any + 'static)>>>) -> Box<dyn Future<Output=Box<dyn Observer<Value=Box<dyn Any>, Output = FinishedObservation<Box<dyn Any>>>>> + 's> {
                    Box::new(async {
                        let (spawn, observer) = task.spawn_local_objsafe(self);
                        let pinned_spawn = Box::pin(spawn);
                        self.0.push(pinned_spawn);
                        Box::new(observer) as Box<dyn Observer<Value=Box<dyn Any>, Output=FinishedObservation<Box<dyn Any>>>>
                    })
                }


                fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> {
                    todo!()
                }
            }
        }
    }