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
use PhantomData;
use Either;
use crateCoro;
use crateFixedPointCoro;
use crateSuspended;
use crateSuspendedVisitor;
/// Weaves two fixed-point coroutines together bidirectionally, feeding the
/// yields of one as inputs to the other until one of them returns.
///
/// This function executes a bidirectional composition between two coroutines:
/// - `coro_a` takes inputs of type `I` and yields values of type `Y`
/// - `coro_b` takes inputs of type `Y` and yields values of type `I`
///
/// The weaving process:
/// 1. Feeds `initial_input` to `coro_a`
/// 2. If `coro_a` yields `y`, passes it to `coro_b`
/// 3. If `coro_b` yields `i`, passes it back to `coro_a`
/// 4. Continues until either coroutine returns
///
/// # Returns
///
/// An `Either` indicating which coroutine completed first:
/// - `Either::Left((r1, remaining_b))` if `coro_a` returned `r1` first
/// - `Either::Right((r2, remaining_a))` if `coro_b` returned `r2` first
///
/// The "remaining" coroutine is left in whatever state it was in when the
/// other coroutine completed, allowing it to potentially be resumed later.
///
/// # Requirements
///
/// Both coroutines must be fixed-point coroutines (`FixedPointCoro`), meaning
/// their `Next` type is `Self`. This constraint is necessary for the result
/// type of the remainder coroutines to be well-defined. If either coroutine
/// were not fixed-point, then it would not be known whether the remainder of
/// that coroutine, at the time the other returns, would be e.g. `A`, or
/// `A::Next`, or `A::Next::Next`, etc.
///
/// # Examples
///
/// ## Producer-consumer with backpressure
///
/// ```rust
/// use core::ops::ControlFlow;
///
/// use cocoro::FixedPointCoro;
/// use cocoro::Void;
/// use cocoro::from_control_flow;
/// use cocoro::weave;
/// use cocoro::yield_with;
/// use either::Either;
///
/// // Data producer that yields items when requested
/// fn data_producer() -> impl FixedPointCoro<(), &'static str, Void> {
/// let items = ["task1", "task2", "task3", "task4"];
/// let mut index = 0;
/// yield_with(move |()| {
/// let item = items[index % items.len()];
/// index += 1;
/// item
/// })
/// }
///
/// // Worker that processes items and signals readiness for more
/// fn worker() -> impl FixedPointCoro<&'static str, (), &'static str> {
/// let mut processed = 0;
/// from_control_flow(move |task: &str| {
/// processed += 1;
/// // Simulate processing time/cost - stop after 3 items
/// if processed >= 3 {
/// ControlFlow::Break("worker finished")
/// } else {
/// // Signal ready for next item
/// ControlFlow::Continue(())
/// }
/// })
/// }
///
/// // Because the producer never returns, the worker will always finish first
/// let Either::Right((msg, _producer)) = weave(data_producer(), worker(), ());
/// assert_eq!(msg, "worker finished");
/// ```
///
/// ## Request-response protocol
///
/// ```rust
/// use core::ops::ControlFlow;
///
/// use cocoro::FixedPointCoro;
/// use cocoro::from_control_flow;
/// use cocoro::weave;
/// use either::Either;
///
/// #[derive(PartialEq, Debug)]
/// enum Request {
/// Get(u32),
/// Put(u32, &'static str),
/// }
///
/// #[derive(PartialEq, Debug)]
/// enum Response {
/// Value(Option<&'static str>),
/// Ok,
/// Error(&'static str),
/// }
///
/// // Client that sends requests and processes responses
/// fn client() -> impl FixedPointCoro<Response, Request, &'static str> {
/// let mut step = 0;
/// from_control_flow(move |response: Response| {
/// match step {
/// 0 => {
/// // First request: put a value
/// step = 1;
/// ControlFlow::Continue(Request::Put(42, "hello"))
/// }
/// 1 => {
/// // Expect OK response, then send get request
/// if response == Response::Ok {
/// step = 2;
/// ControlFlow::Continue(Request::Get(42))
/// } else {
/// ControlFlow::Break("expected Ok response")
/// }
/// }
/// 2 => {
/// // Process the retrieved value
/// if response == Response::Value(Some("hello")) {
/// ControlFlow::Break("success")
/// } else {
/// ControlFlow::Break("unexpected value")
/// }
/// }
/// _ => ControlFlow::Break("protocol error"),
/// }
/// })
/// }
///
/// // Server that processes requests and sends responses
/// fn server() -> impl FixedPointCoro<Request, Response, &'static str> {
/// let mut storage = None;
/// from_control_flow(move |request: Request| match request {
/// Request::Put(42, value) => {
/// storage = Some(value);
/// ControlFlow::Continue(Response::Ok)
/// }
/// Request::Get(42) => ControlFlow::Continue(Response::Value(storage)),
/// _ => ControlFlow::Break("server error"),
/// })
/// }
///
/// // Start with a dummy response to kick off the client state machine
/// match weave(client(), server(), Response::Error("")) {
/// Either::Left((msg, _)) => assert_eq!(msg, "success"),
/// Either::Right((msg, _)) => {
/// panic!("server should not finish first: {}", msg)
/// }
/// }
/// ```
///
/// ## Filtering with early termination
///
/// ```rust
/// use core::ops::ControlFlow;
///
/// use cocoro::FixedPointCoro;
/// use cocoro::Void;
/// use cocoro::from_control_flow;
/// use cocoro::weave;
/// use cocoro::yield_with;
/// use either::Either;
///
/// // Stream of data items
/// fn data_stream() -> impl FixedPointCoro<(), i32, Void> {
/// let items = [1, 7, 3, 12, 5, 8, 15, 2];
/// let mut index = 0;
/// yield_with(move |()| {
/// let item = items[index % items.len()];
/// index += 1;
/// item
/// })
/// }
///
/// // Filter that stops when it finds the first item > 10
/// fn find_first_large() -> impl FixedPointCoro<i32, (), i32> {
/// from_control_flow(move |item: i32| {
/// if item > 10 {
/// ControlFlow::Break(item) // Found it!
/// } else {
/// ControlFlow::Continue(()) // Keep searching
/// }
/// })
/// }
///
/// // Since the data stream never returns, the filter will always finish first
/// let c = data_stream();
/// let Either::Right((item, c)) = weave(c, find_first_large(), ());
/// assert_eq!(item, 12); // First item > 10 in the sequence
/// // And you can do it again with the remaining data stream:
/// let Either::Right((item, _)) = weave(c, find_first_large(), ());
/// assert_eq!(item, 15); // Next item > 10 in the remaining sequence
/// ```
///
/// ## Predicate-based filtering
///
/// ```rust
/// use core::ops::ControlFlow;
///
/// use cocoro::FixedPointCoro;
/// use cocoro::Void;
/// use cocoro::from_control_flow;
/// use cocoro::weave;
/// use cocoro::yield_with;
/// use either::Either;
///
/// // Source of strings
/// fn string_source() -> impl FixedPointCoro<(), &'static str, Void> {
/// let words = ["apple", "banana", "apricot", "cherry", "avocado"];
/// let mut index = 0;
/// yield_with(move |()| {
/// let word = words[index % words.len()];
/// index += 1;
/// word
/// })
/// }
///
/// // Collector that gathers words starting with 'a' until it has 3
/// fn collect_a_words()
/// -> impl FixedPointCoro<&'static str, (), Vec<&'static str>> {
/// let mut collected = Vec::new();
/// from_control_flow(move |word: &str| {
/// if word.starts_with('a') {
/// collected.push(word);
/// if collected.len() >= 3 {
/// ControlFlow::Break(collected.clone())
/// } else {
/// ControlFlow::Continue(())
/// }
/// } else {
/// ControlFlow::Continue(()) // Skip non-matching items
/// }
/// })
/// }
///
/// // The collector will finish first with exactly 3 'a' words
/// let Either::Right((words, _source)) =
/// weave(string_source(), collect_a_words(), ());
/// assert_eq!(words, vec!["apple", "apricot", "avocado"]);
/// ```
/// A consumer that handles the result of a bidirectional coroutine weaving.
///
/// This trait allows handling both possible outcomes of [`weave_cps`] without
/// requiring the remainder coroutines to be the same concrete type. The
/// consumer is called exactly once with either:
/// - `on_left(r1, remaining_b)` if the first coroutine returned first
/// - `on_right(r2, remaining_a)` if the second coroutine returned first
///
/// Since the methods consume `self`, the consumer can only be used once,
/// allowing it to safely move captured data into either branch.
/// Continuation-passing style version of [`weave`] that doesn't require
/// fixed-point coroutines.
///
/// This function executes bidirectional composition between two coroutines
/// and passes the result to a consumer. Unlike [`weave`], this version can
/// work with any coroutines (not just `FixedPointCoro`) because the consumer
/// is polymorphic over the concrete types of remainder coroutines.
///
/// # Examples
///
/// ## Racing algorithms with CPS flexibility
///
/// ```rust
/// use core::ops::ControlFlow;
///
/// use cocoro::Coro;
/// use cocoro::WeaveConsumer;
/// use cocoro::from_control_flow;
/// use cocoro::weave_cps;
///
/// // Consumer that returns the winning result
/// struct TakeWinner;
/// impl<'a> WeaveConsumer<i32, i32, &'a str, &'a str> for TakeWinner {
/// type Out = &'a str;
///
/// fn on_left<B: Coro<i32, i32, &'a str>>(
/// self,
/// result: &'a str,
/// _: B,
/// ) -> &'a str {
/// result // Doubler won
/// }
///
/// fn on_right<A: Coro<i32, i32, &'a str>>(
/// self,
/// result: &'a str,
/// _: A,
/// ) -> &'a str {
/// result // Incrementer won
/// }
/// }
///
/// // Algorithm 1: Double until > 50, then return name
/// let doubler = from_control_flow(|x: i32| {
/// let next = x * 2;
/// if next > 50 {
/// ControlFlow::Break("doubler")
/// } else {
/// ControlFlow::Continue(next)
/// }
/// });
///
/// // Algorithm 2: Add 7 until > 50, then return name
/// let incrementer = from_control_flow(|x: i32| {
/// let next = x + 7;
/// if next > 50 {
/// ControlFlow::Break("incrementer")
/// } else {
/// ControlFlow::Continue(next)
/// }
/// });
///
/// // Race starting from 5: doubler (5→10→20→40→80)
/// // vs incrementer (5→12→19→26→33→40→47→54)
/// let winner = weave_cps(doubler, incrementer, 5, TakeWinner);
/// assert_eq!(winner, "doubler"); // Doubler reaches >50 in fewer steps
/// ```