simple_coro 0.1.5

(ab)using async/await to write simple state-machine based coroutines
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
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
#![doc = include_str!("../docs.md")]
#![warn(
    clippy::complexity,
    clippy::correctness,
    clippy::style,
    future_incompatible,
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    rustdoc::all,
    clippy::undocumented_unsafe_blocks
)]

use core::{
    fmt,
    future::Future,
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

/// A future that can be executed as a [Coro].
/// See [AsCoro] and [IntoCoro] for details.
///
/// # Panics
/// Calls to async methods or functions that attempt to make use of a [Waker] will panic.
pub type CoroFn<S, R, F> = fn(Handle<S, R>) -> F;

/// A type that can construct a [Coro].
///
/// If you need to make use of data held within `self` in order to produce your [CoroFn] then you
/// should look at implementing [IntoCoro] instead.
///
/// # Example
/// ```rust
/// # use simple_coro::{AsCoro, Handle};
/// // Implementing a simple counter using a coroutine (equivalent to std::iter::from_fn)
/// struct Counter<const N: usize>;
///
/// impl<const N: usize> AsCoro for Counter<N> {
///     type Snd = usize;
///     type Rcv = ();
///     type Out = ();
///
///     async fn as_coro_fn(handle: Handle<usize>) {
///         for n in 0..N {
///             handle.yield_value(n).await
///         }
///     }
/// }
///
///
/// let nums: Vec<usize> = Counter::<6>::as_coro().collect();
/// assert_eq!(nums, vec![0, 1, 2, 3, 4, 5]);
/// ```
pub trait AsCoro {
    /// The type that will be sent at each await point
    type Snd: Unpin + 'static;
    /// The type expected to be received at each await point
    type Rcv: Unpin;
    /// The output of running the coroutine to completion
    type Out;

    /// Return a future that can be executed by calling [AsCoro::as_coro] to convert this type into
    /// a [Coro] that can be run to completion.
    ///
    /// # Panics
    /// Calls to async methods or functions that attempt to make use of a [Waker] will panic.
    fn as_coro_fn(handle: Handle<Self::Snd, Self::Rcv>) -> impl Future<Output = Self::Out>;

    /// Initialize a new [Coro] using this type as a constructor.
    fn as_coro() -> ReadyCoro<Self::Snd, Self::Rcv, Self::Out, impl Future<Output = Self::Out>> {
        Coro {
            _lifecycle: Ready,
            state: SharedState::default(),
            fut: Box::pin(Self::as_coro_fn(Handle {
                _snd: PhantomData,
                _rcv: PhantomData,
            })),
        }
    }
}

/// A type that can be converted into a [Coro] from a value.
///
/// If you don't need to make use of data held within `self` in order to produce your [CoroFn] then
/// you should look at implementing [AsCoro] instead.
///
/// ```rust
/// # use simple_coro::{IntoCoro, Handle};
/// struct Echo<T> {
///     initial: T,
/// }
///
/// impl<T: Unpin + 'static> IntoCoro for Echo<T> {
///     type Snd = T;
///     type Rcv = T;
///     type Out = ();
///
///     async fn into_coro_fn(self, handle: Handle<T, T>) {
///         let mut val = self.initial;
///         loop {
///             val = handle.yield_value(val).await;
///         }
///     }
/// }
/// ```
pub trait IntoCoro: Sized {
    /// The type that will be sent at each await point
    type Snd: Unpin + 'static;
    /// The type expected to be received at each await point
    type Rcv: Unpin;
    /// The output of running the coroutine to completion
    type Out;

    /// Provide a future that can be executed by calling [IntoCoro::into_coro] to convert this type
    /// into a [Coro] that can be run to completion.
    ///
    /// # Panics
    /// Calls to async methods or functions that attempt to make use of a [Waker] will panic.
    fn into_coro_fn(self, handle: Handle<Self::Snd, Self::Rcv>) -> impl Future<Output = Self::Out>;

    /// Initialize a new [Coro] from a value.
    fn into_coro(
        self,
    ) -> ReadyCoro<Self::Snd, Self::Rcv, Self::Out, impl Future<Output = Self::Out>> {
        Coro {
            _lifecycle: Ready,
            state: SharedState::default(),
            fut: Box::pin(self.into_coro_fn(Handle {
                _snd: PhantomData,
                _rcv: PhantomData,
            })),
        }
    }

    /// Initialize a new [Coro] with a type erased `Future` from a value.
    fn into_dyn_coro(
        self,
    ) -> ReadyCoro<Self::Snd, Self::Rcv, Self::Out, dyn Future<Output = Self::Out>>
    where
        Self: 'static,
        Self::Out: 'static,
    {
        Coro {
            _lifecycle: Ready,
            state: SharedState::default(),
            fut: Box::pin(self.into_coro_fn(Handle {
                _snd: PhantomData,
                _rcv: PhantomData,
            })),
        }
    }
}

// Closures with the correct signature can be directly converted into a [Coro].
impl<F, S, R, Fut, O> From<F> for ReadyCoro<S, R, O, Fut>
where
    F: FnOnce(Handle<S, R>) -> Fut,
    S: Unpin + 'static,
    R: Unpin,
    Fut: Future<Output = O>,
{
    fn from(f: F) -> Self {
        Coro {
            _lifecycle: Ready,
            state: SharedState::default(),
            fut: Box::pin((f)(Handle {
                _snd: PhantomData,
                _rcv: PhantomData,
            })),
        }
    }
}

impl<S, R, O> ReadyCoro<S, R, O, dyn Future<Output = O>>
where
    S: Unpin + 'static,
    R: Unpin,
{
    /// Create a new [Coro] with a type erased `Future`.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{ReadyCoro, Handle};
    /// let coro: ReadyCoro<usize, bool, &'static str, dyn Future<Output = _>> = ReadyCoro::from_dyn(|handle: Handle<usize, bool>| async move {
    ///     let result = handle.yield_value(42).await;
    ///     if result { "yes" } else { "no" }
    /// });
    /// ```
    pub fn from_dyn<F, Fut>(f: F) -> Self
    where
        F: FnOnce(Handle<S, R>) -> Fut,
        Fut: Future<Output = O> + 'static,
    {
        Coro {
            _lifecycle: Ready,
            state: SharedState::default(),
            fut: Box::pin((f)(Handle {
                _snd: PhantomData,
                _rcv: PhantomData,
            })),
        }
    }
}

const DENY_FUT: &str = "a Coro is not permitted to await a future that uses an arbitrary Waker";
static WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
    |_| panic!("{DENY_FUT}"),
    |_| panic!("{DENY_FUT}"),
    |_| panic!("{DENY_FUT}"),
    |_| {},
);

#[derive(Debug, Clone)]
struct SharedState<S, R>
where
    S: 'static,
{
    s: Option<S>,
    r: Option<R>,
}

impl<S, R> Default for SharedState<S, R> {
    fn default() -> Self {
        Self { s: None, r: None }
    }
}

/// The lifecycle state of a running [Coro]: either [Pending] or [Ready].
///
/// This is used as a typestate to enforce that all yields from a [Coro] are handled before they
/// are resumed.
pub trait Lifecycle: fmt::Debug {}

/// A [Lifecycle] marker denoting that a [Coro] is ready for the next call to [resume][Coro::resume].
#[derive(Debug)]
pub struct Ready;
impl Lifecycle for Ready {}

/// A [Lifecycle] marker denoting that a [Coro] is awaiting a call to [send][Coro::send].
#[derive(Debug)]
pub struct Pending;
impl Lifecycle for Pending {}

/// A [Coro] that is ready to be resumed by calling [resume][Coro::resume].
pub type ReadyCoro<S, R, O, F> = Coro<S, R, O, F, Ready>;

/// A [Coro] that is pending a response from [send][Coro::send].
pub type PendingCoro<S, R, O, F> = Coro<S, R, O, F, Pending>;

/// A running coroutine that can make progress by calling [resume][Coro::resume].
///
/// A `Coro` can be constructed directly from a [CoroFn] using `Coro::from` or via either of the
/// [AsCoro] or [IntoCoro] traits.
///
///
/// ### Constructing a Coro directly from an async closure
/// ```rust
/// use simple_coro::{Coro, CoroState, Handle};
///
/// let mut coro = Coro::from(async |handle: Handle<usize, bool>| {
///     let say_hello: bool = handle.yield_value(42).await;
///     if say_hello {
///         "Hello, World!"
///     } else {
///         "Goodbye cruel world!"
///     }
/// });
///
/// coro = coro.resume().unwrap_pending(|n| {
///     assert_eq!(n, 42);
///     true
/// });
///
/// let msg = coro.resume().unwrap();
/// assert_eq!(msg, "Hello, World!");
/// ```
///
/// ### Implementing [IntoCoro] for types that need access to internal state
/// ```rust
/// use simple_coro::{Coro, CoroState, Handle, IntoCoro};
///
/// struct Echo<T> {
///     initial: T,
/// }
///
/// impl<T: Unpin + 'static> IntoCoro for Echo<T> {
///     type Snd = T;
///     type Rcv = T;
///     type Out = ();
///
///     async fn into_coro_fn(self, handle: Handle<T, T>) {
///         let mut val = self.initial;
///         loop {
///             val = handle.yield_value(val).await;
///         }
///     }
/// }
///
/// let mut coro = Echo { initial: "ping" }.into_coro();
/// coro = coro.resume().unwrap_pending(|s| {
///     assert_eq!(s, "ping");
///     "pong"
/// });
///
/// coro = coro.resume().unwrap_pending(|s| {
///     assert_eq!(s, "pong");
///     "ping"
/// });
/// ```
///
/// ### Implementing [AsCoro] for types that serve as constructors
/// ```rust
/// use simple_coro::{Coro, AsCoro, Handle, CoroState};
/// use std::io::{self, Read};
///
/// async fn read_9p_u16(handle: Handle<usize, Vec<u8>>) -> io::Result<u16> {
///     let n = size_of::<u16>();
///     let buf = handle.yield_value(n).await;
///     let data = buf[0..n].try_into().unwrap();
///
///     Ok(u16::from_le_bytes(data))
/// }
///
/// struct NinepString;
///
/// impl AsCoro for NinepString {
///     type Snd = usize;
///     type Rcv = Vec<u8>;
///     type Out = io::Result<String>;
///
///     async fn as_coro_fn(handle: Handle<usize, Vec<u8>>) -> io::Result<String> {
///         let len = handle.yield_from(read_9p_u16).await? as usize;
///         let buf = handle.yield_value(len).await;
///
///         String::from_utf8(buf)
///             .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
///     }
/// }
///
/// let mut cur = io::Cursor::new(vec![
///     0x0d, 0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c,
/// ]);
///
/// let s = NinepString::as_coro().run_sync(|n| {
///     let mut buf = vec![0; n];
///     cur.read_exact(&mut buf).unwrap();
///     buf
/// })
/// .unwrap();
///
/// assert_eq!(s, "Hello, 世界");
/// ```
pub struct Coro<S, R, O, F: ?Sized, L>
where
    S: Unpin + 'static,
    R: Unpin,
    F: Future<Output = O>,
    L: Lifecycle,
{
    _lifecycle: L,
    state: SharedState<S, R>,
    fut: Pin<Box<F>>,
}

impl<S, R, O, F: ?Sized, L> fmt::Debug for Coro<S, R, O, F, L>
where
    S: Unpin,
    R: Unpin,
    F: Future<Output = O>,
    L: Lifecycle,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Coro")
            .field("lifecycle", &self._lifecycle)
            .finish()
    }
}

impl<S, R, O, Fut: ?Sized> Coro<S, R, O, Fut, Ready>
where
    S: Unpin,
    R: Unpin,
    Fut: Future<Output = O>,
{
    /// Run this [Coro] to completion using the provided synchronous step function. If you need to
    /// make use of an asynchronous step function you should use [run_async][Coro::run_async].
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, Handle};
    /// let my_coro = Coro::from(async |handle: Handle<usize, Option<usize>>| {
    ///     let pos = handle.yield_value(42).await;
    ///     assert_eq!(pos, Some(5));
    ///     let pos = handle.yield_value(17).await;
    ///     assert_eq!(pos, Some(2));
    ///     let pos = handle.yield_value(68).await;
    ///     assert!(pos.is_none());
    ///
    ///     "done"
    /// });
    ///
    /// let vec = vec![5, 3, 17, 29, 103, 42, 55];
    /// let res = my_coro.run_sync(|n| vec.iter().position(|&x| x == n));
    /// assert_eq!(res, "done");
    /// ```
    ///
    /// Equivalent to:
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, HandOwl};
    /// # let my_coro = Coro::from(async |_: HandOwl| {});
    /// # let step_fn = |unit| unit;
    /// let mut coro = my_coro;
    /// loop {
    ///     coro = match coro.resume() {
    ///         CoroState::Complete(res) => return res,
    ///         CoroState::Pending(c, s) => c.send((step_fn)(s)),
    ///     };
    /// }
    /// ```
    pub fn run_sync<F>(self, mut step_fn: F) -> O
    where
        F: FnMut(S) -> R,
    {
        let mut coro = self;
        loop {
            coro = match coro.resume() {
                CoroState::Complete(res) => return res,
                CoroState::Pending(c, s) => c.send((step_fn)(s)),
            };
        }
    }

    /// Run this [Coro] to completion using the provided asynchronous step function. If you want to
    /// make use of an synchronous step function you should use [run_sync][Coro::run_sync].
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, Handle};
    /// # tokio_test::block_on(async {
    /// let my_coro = Coro::from(async |handle: Handle<usize, Option<usize>>| {
    ///     let pos = handle.yield_value(42).await;
    ///     assert_eq!(pos, Some(5));
    ///     let pos = handle.yield_value(17).await;
    ///     assert_eq!(pos, Some(2));
    ///     let pos = handle.yield_value(68).await;
    ///     assert!(pos.is_none());
    ///
    ///     "done"
    /// });
    ///
    /// let vec = vec![5, 3, 17, 29, 103, 42, 55];
    /// let res = my_coro.run_async(async |n| vec.iter().position(|&x| x == n)).await;
    /// assert_eq!(res, "done");
    /// # })
    /// ```
    ///
    /// Equivalent to:
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, HandOwl};
    /// # tokio_test::block_on(async {
    /// # let my_coro = Coro::from(async |_: HandOwl| {});
    /// # let step_fn = async |unit| unit;
    /// let mut coro = my_coro;
    /// loop {
    ///     coro = match coro.resume() {
    ///         CoroState::Complete(res) => return res,
    ///         CoroState::Pending(c, s) => c.send((step_fn)(s).await),
    ///     };
    /// }
    /// # })
    /// ```
    pub async fn run_async<F>(self, mut step_fn: F) -> O
    where
        F: AsyncFnMut(S) -> R,
    {
        let mut coro = self;
        loop {
            coro = match coro.resume() {
                CoroState::Complete(res) => return res,
                CoroState::Pending(c, s) => c.send((step_fn)(s).await),
            };
        }
    }

    /// Run the [Coro] to its next yield point, returning a [CoroState].
    ///
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, HandOwl};
    /// # let coro = Coro::from(async |_: HandOwl| {});
    /// match coro.resume() {
    ///     CoroState::Complete(res) => println!("coroutine completed with value: {res:?}"),
    ///     CoroState::Pending(pending_coro, val) => println!("coroutine yielded {val:?}"),
    /// };
    /// ```
    pub fn resume(mut self) -> CoroState<S, R, O, Fut> {
        // SAFETY: we never use this waker for its intended purpose
        let waker = unsafe {
            Waker::from_raw(RawWaker::new(
                &self.state as *const SharedState<S, R> as *const (),
                &WAKER_VTABLE,
            ))
        };
        let mut ctx = Context::from_waker(&waker);
        match self.fut.as_mut().poll(&mut ctx) {
            Poll::Ready(val) => CoroState::Complete(val),
            Poll::Pending => {
                let s = self.state.s.take().unwrap_or_else(|| panic!("{DENY_FUT}"));
                let sm = Coro {
                    _lifecycle: Pending,
                    state: self.state,
                    fut: self.fut,
                };

                CoroState::Pending(sm, s)
            }
        }
    }
}

impl<S, R, O, F: ?Sized> Coro<S, R, O, F, Pending>
where
    S: Unpin,
    R: Unpin,
    F: Future<Output = O>,
{
    /// Send a response to this [Coro] following a call to [Handle::yield_value].
    ///
    /// Calling this method coverts a [PendingCoro] into a [ReadyCoro], allowing it to be resumed
    /// again (and reassigned to an existing variable).
    ///
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, Handle};
    /// let mut coro = Coro::from(async |handle: Handle<(), usize>| {
    ///     let n = handle.yield_value(()).await;
    ///     assert_eq!(n, 70);
    /// });
    ///
    /// coro = match coro.resume() {
    ///     CoroState::Pending(pending_coro, _) => pending_coro.send(70),
    ///     CoroState::Complete(_) => return,
    /// };
    /// ```
    pub fn send(mut self, r: R) -> ReadyCoro<S, R, O, F> {
        self.state.r = Some(r);

        Coro {
            _lifecycle: Ready,
            state: self.state,
            fut: self.fut,
        }
    }
}

/// A Generator is a simplified [Coro] that only emits values and does not return a final value.
/// As such, it can be used as a convenient way to write an [Iterator].
///
/// # Example
/// ```rust
/// # use simple_coro::{Generator, Handle};
/// let counter = |k: usize| {
///     Generator::from(move |handle: Handle<usize>| async move {
///         for n in 0..k {
///             handle.yield_value(n).await;
///         }
///     })
/// };
///
/// let nums: Vec<usize> = counter(6).collect();
/// assert_eq!(nums, vec![0, 1, 2, 3, 4, 5]);
/// ```
pub type Generator<T, F> = Coro<T, (), (), F, Ready>;

impl<T, F: ?Sized> Iterator for Generator<T, F>
where
    T: Unpin,
    F: Future<Output = ()>,
{
    type Item = T;

    /// The impl here is a modified version of the [Coro::resume] and [Coro::send] methods that
    /// avoids flipping the typestate between [Ready] and [Pending].
    fn next(&mut self) -> Option<T> {
        // SAFETY: we never use this waker for its intended purpose
        let waker = unsafe {
            Waker::from_raw(RawWaker::new(
                &self.state as *const SharedState<T, ()> as *const (),
                &WAKER_VTABLE,
            ))
        };
        let mut ctx = Context::from_waker(&waker);
        match self.fut.as_mut().poll(&mut ctx) {
            Poll::Pending => {
                let val = self.state.s.take().unwrap_or_else(|| panic!("{DENY_FUT}"));
                self.state.r = Some(());

                Some(val)
            }
            Poll::Ready(()) => None,
        }
    }
}

/// The intermediate state of a [Coro] while it is executing
#[derive(Debug)]
#[must_use]
pub enum CoroState<S, R, T, F: ?Sized>
where
    S: Unpin + 'static,
    R: Unpin,
    F: Future<Output = T>,
{
    /// The [Coro] yielded via [yield_value][Handle::yield_value]. Call the [send][Coro::send]
    /// method on the inner [PendingCoro] to send a value back into the coroutine and convert
    /// it back to a [ReadyCoro] which can be [resumed][Coro::resume].
    Pending(PendingCoro<S, R, T, F>, S),
    /// The [Coro] is now complete and has returned a value.
    Complete(T),
}

impl<S, R, T, F: ?Sized> CoroState<S, R, T, F>
where
    S: Unpin + 'static,
    R: Unpin,
    F: Future<Output = T>,
{
    /// Returns `true` if this is a [Pending][CoroState::Pending] value.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, Handle};
    /// let mut coro = Coro::from(async |handle: Handle<(), usize>| {
    ///     let n = handle.yield_value(()).await;
    ///     assert_eq!(n, 70);
    /// });
    ///
    /// let state = coro.resume();
    /// assert_eq!(state.is_pending(), true);
    ///
    /// coro = state.unwrap_pending(|_| 70);
    ///
    /// let state = coro.resume();
    /// assert_eq!(state.is_pending(), false);
    /// ```
    pub fn is_pending(&self) -> bool {
        matches!(self, &Self::Pending(_, _))
    }

    /// Returns `true` if this is a [Complete][CoroState::Complete] value.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, Handle};
    /// let mut coro = Coro::from(async |handle: Handle<(), usize>| {
    ///     let n = handle.yield_value(()).await;
    ///     assert_eq!(n, 70);
    /// });
    ///
    /// let state = coro.resume();
    /// assert_eq!(state.is_complete(), false);
    ///
    /// coro = state.unwrap_pending(|_| 70);
    ///
    /// let state = coro.resume();
    /// assert_eq!(state.is_complete(), true);
    /// ```
    pub fn is_complete(&self) -> bool {
        matches!(self, &Self::Complete(_))
    }

    /// Assume that this value is [Pending][CoroState::Pending] and send a response to the
    /// underlying [Coro] using the provided mapping function to unwrap it into a [ReadyCoro].
    ///
    /// # Panics
    /// This will panic if the value was [Complete][CoroState::Complete].
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, Handle};
    /// let mut coro = Coro::from(async |handle: Handle<(), usize>| {
    ///     let n = handle.yield_value(()).await;
    ///     assert_eq!(n, 70);
    /// });
    ///
    /// coro = coro.resume().unwrap_pending(|_| 70);
    /// ```
    pub fn unwrap_pending(self, f: impl Fn(S) -> R) -> ReadyCoro<S, R, T, F> {
        match self {
            Self::Pending(coro, s) => coro.send((f)(s)),
            Self::Complete(_) => {
                panic!("called `CoroState::unwrap_pending` on a `Complete` value")
            }
        }
    }

    /// Assume that this value is [Complete][CoroState::Complete] and unwrap it to return the inner
    /// value.
    ///
    /// # Panics
    /// This will panic if the value was [Pending][CoroState::Pending].
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, CoroState, Handle};
    /// let mut coro = Coro::from(async |handle: Handle<(), ()>| {
    ///     "done"
    /// });
    ///
    /// assert_eq!(coro.resume().unwrap(), "done");
    /// ```
    pub fn unwrap(self) -> T {
        match self {
            Self::Pending(_, _) => {
                panic!("called `CoroState::unwrap` on a `Pending` value")
            }
            Self::Complete(t) => t,
        }
    }
}

/// A yield handle to facilitate communication between a [Coro] and the logic driving it.
///
/// The only way to obtain a [Handle] is by constructing a [Coro] (via the [AsCoro::as_coro_fn] or
/// [IntoCoro::into_coro_fn] methods or calling [Coro::from] on an appropriate async function).
#[derive(Debug)]
pub struct Handle<S, R = ()>
where
    S: Unpin,
    R: Unpin,
{
    _snd: PhantomData<S>,
    _rcv: PhantomData<R>,
}

///     ^...^
///    / o,o \
///    |):::(|
///  ====w=w===
#[doc(hidden)]
pub type HandOwl = Handle<(), ()>;

impl<S, R> Clone for Handle<S, R>
where
    S: Unpin + 'static,
    R: Unpin,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<S, R> Copy for Handle<S, R>
where
    S: Unpin + 'static,
    R: Unpin,
{
}

impl<S, R> Handle<S, R>
where
    S: Unpin + 'static,
    R: Unpin,
{
    /// Yield back to the code that owns the [Coro] calling this method, requesting it to
    /// map an `S` into and `R`.
    ///
    /// > This is _not_ a normal [Future] that you can await in an arbitrary async runtime. It is
    /// > shared communication mechanism between a [Coro] and the logic running it.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, Handle};
    /// let coro = Coro::from(async |handle: Handle<&'static str>| {
    ///     handle.yield_value("Hello, World!").await;
    /// });
    ///
    /// coro.resume().unwrap_pending(|s| assert_eq!(s, "Hello, World!"));
    /// ```
    pub async fn yield_value(&self, snd: S) -> R {
        Yield {
            polled: false,
            s: Some(snd),
            _r: PhantomData,
        }
        .await
    }

    /// Defer execution to a value that can be turned into another [Coro] until it completes,
    /// returning the completed value.
    ///
    /// The `Snd` and `Rcv` types for the coroutine you are yielding from must match the types used
    /// by this coroutine. From the point of view of the logic running this [Coro] it will simply
    /// receive a continuous stream of `Snd` values in response to calling [resume][Coro::resume]
    /// with no way to distinguish which coroutine they came from.
    ///
    /// > This is _not_ a normal [Future] that you can await in an arbitrary async runtime. It is
    /// > shared communication mechanism between a [Coro] and the logic running it.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{Coro, Handle};
    /// async fn yield_nums(handle: Handle<usize>) {
    ///     handle.yield_value(1).await;
    ///     handle.yield_value(2).await;
    /// }
    ///
    /// let coro = Coro::from(async |handle: Handle<usize>| {
    ///     handle.yield_value(0).await;
    ///     handle.yield_from(yield_nums).await;
    ///     handle.yield_value(3).await;
    /// });
    ///
    /// let mut buf = Vec::with_capacity(4);
    /// coro.run_sync(|n| buf.push(n));
    ///
    /// assert_eq!(&buf, &[0, 1, 2, 3]);
    /// ```
    pub async fn yield_from<T, C, F>(&self, coro: C) -> T
    where
        C: Into<ReadyCoro<S, R, T, F>>,
        F: Future<Output = T>,
    {
        coro.into().fut.await
    }

    /// Defer execution to a type that can be turned into another [Coro] until it completes,
    /// returning the completed value.
    ///
    /// The `Snd` and `Rcv` types for the coroutine you are yielding from must match the types used
    /// by this coroutine. From the point of view of the logic running this [Coro] it will simply
    /// receive a continuous stream of `Snd` values in response to calling [resume][Coro::resume]
    /// with no way to distinguish which coroutine they came from.
    ///
    /// > This is _not_ a normal [Future] that you can await in an arbitrary async runtime. It is
    /// > shared communication mechanism between a [Coro] and the logic running it.
    ///
    /// # Example
    /// ```rust
    /// # use simple_coro::{AsCoro, Coro, Handle};
    /// struct CoroRange<const FROM: usize, const TO: usize>;
    ///
    /// impl<const FROM: usize, const TO: usize> AsCoro for CoroRange<FROM, TO> {
    ///     type Snd = usize;
    ///     type Rcv = ();
    ///     type Out = ();
    ///
    ///     async fn as_coro_fn(handle: Handle<usize>) {
    ///         for n in FROM..TO {
    ///             handle.yield_value(n).await
    ///         }
    ///     }
    /// }
    ///
    /// let coro = Coro::from(async |handle: Handle<usize>| {
    ///     handle.yield_value(0).await;
    ///     handle.yield_from_type::<CoroRange<1, 3>, _>().await;
    ///     handle.yield_value(3).await;
    /// });
    ///
    /// let mut buf = Vec::with_capacity(4);
    /// coro.run_sync(|n| buf.push(n));
    ///
    /// assert_eq!(&buf, &[0, 1, 2, 3]);
    /// ```
    pub async fn yield_from_type<C, T>(&self) -> T
    where
        C: AsCoro<Snd = S, Rcv = R, Out = T>,
    {
        C::as_coro_fn(*self).await
    }
}

struct Yield<S, R>
where
    S: Unpin + 'static,
    R: Unpin,
{
    polled: bool,
    s: Option<S>,
    _r: PhantomData<R>,
}

impl<S, R> Future for Yield<S, R>
where
    S: Unpin + 'static,
    R: Unpin,
{
    type Output = R;

    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<R> {
        if *ctx.waker().vtable() != WAKER_VTABLE {
            panic!("this future must be awaited inside of a Coro");
        }

        if self.polled {
            // SAFETY: we can only poll this future using a waker wrapping State<S, R> and we only
            // ever access the shared state here or inside of Coro::resume which never execute at
            // the same time.
            let data = unsafe {
                (ctx.waker().data() as *mut () as *mut SharedState<S, R>)
                    .as_mut()
                    .unwrap_unchecked()
                    .r
                    .take()
                    .unwrap_unchecked()
            };

            Poll::Ready(data)
        } else {
            self.polled = true;
            // SAFETY: we can only poll this future using a waker wrapping State<S, R> and we only
            // ever access the shared state here or inside of Coro::resume which never execute at
            // the same time.
            unsafe {
                (ctx.waker().data() as *mut () as *mut SharedState<S, R>)
                    .as_mut()
                    .unwrap_unchecked()
                    .s = Some(self.s.take().unwrap_unchecked());
            };

            Poll::Pending
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        io::{self, Cursor, ErrorKind},
        pin::pin,
        sync::mpsc::channel,
        thread::spawn,
    };

    fn yield_recv_return()
    -> ReadyCoro<usize, bool, &'static str, impl Future<Output = &'static str>> {
        Coro::from(async |handle: Handle<usize, bool>| {
            assert!(handle.yield_value(42).await);

            "hello, world!"
        })
    }

    #[test]
    fn yield_recv_return_works() {
        let mut coro = yield_recv_return();
        coro = coro.resume().unwrap_pending(|n| {
            assert_eq!(n, 42);
            true
        });

        let s = coro.resume().unwrap();
        assert_eq!(s, "hello, world!");
    }

    // This is pretty contrived but worthwhile validating that chaining the unwrap and
    // unwrap_pending methods works fine
    #[test]
    fn coro_state_chaining_works() {
        let s = yield_recv_return()
            .resume()
            .unwrap_pending(|n| {
                assert_eq!(n, 42);
                true
            })
            .resume()
            .unwrap();

        assert_eq!(s, "hello, world!");
    }

    #[test]
    #[should_panic = "called `CoroState::unwrap` on a `Pending` value"]
    fn unwrap_on_pending_panics() {
        yield_recv_return().resume().unwrap();
    }

    #[test]
    #[should_panic = "called `CoroState::unwrap_pending` on a `Complete` value"]
    fn unwrap_pending_on_complete_panics() {
        let mut coro = yield_recv_return();
        coro = coro.resume().unwrap_pending(|n| {
            assert_eq!(n, 42);
            true
        });

        coro.resume().unwrap_pending(|n| {
            assert_eq!(n, 42);
            true
        });
    }

    #[test]
    #[should_panic = "this future must be awaited inside of a Coro"]
    fn manually_polling_yield_panics() {
        let coro = Coro::from(async |handle: Handle<()>| {
            let fut = handle.yield_value(());
            let waker = Waker::noop();
            let mut cx = Context::from_waker(waker);

            let _ = pin!(fut).as_mut().poll(&mut cx);
        });

        let _ = coro.resume();
    }

    #[test]
    fn dyn_future_type_works() {
        let coro = Coro::from_dyn(|handle: Handle<usize, bool>| async move {
            assert!(handle.yield_value(42).await);
            "hello, dyn world!"
        });

        let mut coro = coro;
        coro = coro.resume().unwrap_pending(|n| {
            assert_eq!(n, 42);
            true
        });

        let s = coro.resume().unwrap();
        assert_eq!(s, "hello, dyn world!");
    }

    // Trying to write double_nums as a closure that returns a Coro results in lifetime errors
    // around the lifetime of the coro being longer than the lifetime of the nums reference
    fn double_nums(
        nums: &[usize],
    ) -> ReadyCoro<usize, usize, &'static str, impl Future<Output = &'static str>> {
        Coro::from(async |handle: Handle<usize, usize>| {
            for &n in nums.iter() {
                let doubled = handle.yield_value(n).await;
                assert_eq!(doubled, n * 2);
            }

            "done"
        })
    }

    #[test]
    fn closures_capturing_references_work() {
        let mut coro = double_nums(&[1, 2, 3]);
        loop {
            coro = match coro.resume() {
                CoroState::Pending(c, n) => c.send(n * 2),
                CoroState::Complete(res) => {
                    assert_eq!(res, "done");
                    return;
                }
            };
        }
    }

    #[test]
    fn run_sync_works() {
        let res = double_nums(&[1, 2, 3]).run_sync(|n| n * 2);
        assert_eq!(res, "done");
    }

    #[tokio::test]
    async fn run_async_works() {
        let res = double_nums(&[1, 2, 3]).run_async(async |n| n * 2).await;
        assert_eq!(res, "done");
    }

    // Using const generics to implement a counter generator
    struct Counter<const N: usize>;

    impl<const N: usize> AsCoro for Counter<N> {
        type Snd = usize;
        type Rcv = ();
        type Out = ();

        async fn as_coro_fn(handle: Handle<usize>) {
            for n in 0..N {
                handle.yield_value(n).await
            }
        }
    }

    #[test]
    fn generator_iter_works() {
        let nums: Vec<usize> = Counter::<6>::as_coro().collect();
        assert_eq!(nums, vec![0, 1, 2, 3, 4, 5]);
    }

    #[test]
    fn yield_from_type_works() {
        let coro = Coro::from(async |handle: Handle<usize>| {
            handle.yield_from_type::<Counter<6>, _>().await
        });
        let total: usize = coro.sum();

        assert_eq!(total, 1 + 2 + 3 + 4 + 5);
    }

    // This _doesn't_ work when you are closing over a reference (like in the double_nums case
    // above) due to the Coro capturing a lifetime. Need to work out what is different when you
    // define it as a free function as that works...
    #[test]
    fn capturing_nested_closure_works() {
        let g = |k: usize| {
            Generator::from(move |handle: Handle<usize>| async move {
                for n in 0..k {
                    handle.yield_value(n).await;
                }
            })
        };

        let nums: Vec<usize> = g(6).collect();
        assert_eq!(nums, vec![0, 1, 2, 3, 4, 5]);
    }

    fn tokio_boom() -> ReadyCoro<(), (), &'static str, impl Future<Output = &'static str>> {
        Coro::from(async |_: Handle<()>| {
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;

            "boom!"
        })
    }

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    #[should_panic = "a Coro is not permitted to await a future that uses an arbitrary Waker"]
    async fn awaiting_a_future_that_needs_a_waker_panics() {
        let _ = tokio_boom().resume();
    }

    // This is handled on the tokio side by checking if the tokio runtime is present but tested
    // here to document the difference in the error message received. In both cases (this and the
    // above) awaiting a future that needs a Waker results in a panic.
    #[test]
    #[should_panic = "there is no reactor running, must be called from the context of a Tokio 1.x runtime"]
    fn awaiting_a_tokio_future_panics_outside_of_tokio() {
        let _ = tokio_boom().resume();
    }

    struct Echo<T> {
        initial: T,
    }

    impl<T: Unpin + 'static> IntoCoro for Echo<T> {
        type Snd = T;
        type Rcv = T;
        type Out = ();

        async fn into_coro_fn(self, handle: Handle<T, T>) {
            let mut val = self.initial;
            loop {
                val = handle.yield_value(val).await;
            }
        }
    }

    // Contrived but checking that we are able to pass a Coro between threads and resume it without
    // things exploding in any way. Essentially this is a test that when we have Send Coro that's
    // actually valid.
    #[test]
    fn moving_between_threads_works() {
        let mut ping_pong = Echo { initial: "ping" }.into_coro();
        let (tx1, rx1) = channel();
        let (tx2, rx2) = channel();

        let jh1 = spawn(move || {
            for _ in 0..3 {
                ping_pong = match ping_pong.resume() {
                    CoroState::Pending(c, s) => {
                        assert_eq!(s, "ping");
                        let coro = c.send("pong");
                        tx1.send(coro).unwrap();
                        rx2.recv().unwrap()
                    }
                    CoroState::Complete(_) => break,
                };
            }
        });

        let jh2 = spawn(move || {
            for _ in 0..3 {
                let ping_pong = rx1.recv().unwrap();
                match ping_pong.resume() {
                    CoroState::Pending(c, s) => {
                        assert_eq!(s, "pong");
                        let coro = c.send("ping");
                        tx2.send(coro).unwrap();
                    }
                    CoroState::Complete(_) => break,
                }
            }
        });

        jh1.join().unwrap();
        jh2.join().unwrap();
    }

    // ["Hello", "世界"] in 9p wire format.
    const HELLO_WORLD: [u8; 17] = [
        0x02, 0x00, 0x05, 0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x06, 0x00, 0xe4, 0xb8, 0x96, 0xe7,
        0x95, 0x8c,
    ];

    async fn read_9p_u16(handle: Handle<usize, Vec<u8>>) -> io::Result<u16> {
        let n = size_of::<u16>();
        let buf = handle.yield_value(n).await;
        let data = buf[0..n].try_into().unwrap();

        Ok(u16::from_le_bytes(data))
    }

    async fn read_9p_string(handle: Handle<usize, Vec<u8>>) -> io::Result<String> {
        let len = handle.yield_from(read_9p_u16).await? as usize;
        let buf = handle.yield_value(len).await;

        String::from_utf8(buf).map_err(|e| io::Error::new(ErrorKind::InvalidData, e.to_string()))
    }

    async fn read_9p_string_vec(handle: Handle<usize, Vec<u8>>) -> io::Result<Vec<String>> {
        let len = handle.yield_from(read_9p_u16).await? as usize;
        let mut buf = Vec::with_capacity(len);
        for _ in 0..len {
            buf.push(handle.yield_from(read_9p_string).await?);
        }

        Ok(buf)
    }

    #[test]
    fn nested_yield_from_works() {
        use std::io::Read;

        let mut coro = Coro::from(read_9p_string_vec);
        let mut r = Cursor::new(HELLO_WORLD.to_vec());

        loop {
            coro = match coro.resume() {
                CoroState::Complete(parsed) => {
                    assert_eq!(parsed.unwrap(), &["Hello", "世界"]);
                    return;
                }
                CoroState::Pending(c, n) => c.send({
                    let mut buf = vec![0; n];
                    r.read_exact(&mut buf).unwrap();
                    buf
                }),
            };
        }
    }

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    async fn nested_yield_from_works_with_async() {
        use tokio::io::AsyncReadExt;

        let mut coro = Coro::from(read_9p_string_vec);
        let mut r = Cursor::new(HELLO_WORLD.to_vec());

        loop {
            coro = match coro.resume() {
                CoroState::Complete(parsed) => {
                    assert_eq!(parsed.unwrap(), &["Hello", "世界"]);
                    return;
                }
                CoroState::Pending(c, n) => c.send({
                    let mut buf = vec![0; n];
                    r.read_exact(&mut buf).await.unwrap();
                    buf
                }),
            };
        }
    }

    #[test]
    fn run_sync_works_with_nested_yields() {
        use std::io::Read;

        let mut r = Cursor::new(HELLO_WORLD.to_vec());
        let parsed = Coro::from(read_9p_string_vec)
            .run_sync(|n| {
                let mut buf = vec![0; n];
                r.read_exact(&mut buf).unwrap();
                buf
            })
            .expect("parsing to be successful");

        assert_eq!(parsed, &["Hello", "世界"]);
    }
}