async-codegen 0.12.1

Minimalist async-IO code generation framework.
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
/*
 * Copyright © 2025 Anand Beh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::common::SequenceConfig;
use crate::context::Context;
use crate::{IoOutput, Output, Writable, WritableSeq};
use std::convert::Infallible;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::pin::pin;
use std::task::{Poll, Waker};

/// A wrapper intended to be used as a [SequenceConfig].
/// The tuple value should be a function that returns a writable for the data type.
pub struct WritableFromFunction<F>(pub F);

impl<F, T, W, O> SequenceConfig<T, O> for WritableFromFunction<F>
where
    O: Output,
    F: Fn(&T) -> W,
    W: Writable<O>,
{
    async fn write_datum(&self, datum: &T, output: &mut O) -> Result<(), O::Error> {
        let writable = (&self.0)(datum);
        writable.write_to(output).await
    }
}

/// An IO implementation that just writes to a string. The futures produced from methods
/// like [IoOutput::write] are complete instantly, and no errors are produced.
pub struct InMemoryIo<'s>(pub &'s mut String);

impl IoOutput for InMemoryIo<'_> {
    type Error = Infallible;

    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
        self.0.push_str(value);
        Ok(())
    }
}

/// An output implementation that just writes to a string.
///
/// This output itself produces no errors and the write futures complete instantly. It uses
/// [InMemoryIo] as the IO type.
///
/// However, for compatibility with higher level code that uses a different error type, the
/// error type can be selected by the type parameter `Err`. Note that `Err` must be convertible
/// from [Infallible]. Regardless of the error type chosen, it will never be returned from this
/// output itself.
pub struct InMemoryOutput<Ctx, Err = Infallible> {
    buf: String,
    context: Ctx,
    error_type: PhantomData<fn(Infallible) -> Err>,
}

impl<Ctx, Err> InMemoryOutput<Ctx, Err> {
    pub fn new(context: Ctx) -> Self {
        Self {
            buf: String::new(),
            context,
            error_type: PhantomData,
        }
    }
}

impl<Ctx, Err> Output for InMemoryOutput<Ctx, Err>
where
    Ctx: Context,
    Err: From<Infallible>,
{
    type Io<'b>
        = InMemoryIo<'b>
    where
        Self: 'b;
    type Ctx = Ctx;
    type Error = Err;

    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
        self.buf.push_str(value);
        Ok(())
    }

    fn split(&mut self) -> (Self::Io<'_>, &Self::Ctx) {
        (InMemoryIo(&mut self.buf), &self.context)
    }

    fn context(&self) -> &Self::Ctx {
        &self.context
    }
}

impl<Ctx, Err> InMemoryOutput<Ctx, Err>
where
    Ctx: Context,
    Err: From<Infallible>,
{
    /// Gets the string output of a single writable.
    ///
    /// Assumes that the only source of async is this [InMemoryOutput] itself, i.e. the writable
    /// will never return a pending future unless the output used with it returns a pending future.
    /// Because of its async-rejecting nature, this function is intended for testing purposes.
    ///
    /// **Panics** if the writable returns a pending future (particularly, this may happen if
    /// a writable introduces its own async computations that do not come from the output)
    pub fn try_print_output<W>(context: Ctx, writable: &W) -> Result<String, Err>
    where
        W: Writable<Self>,
    {
        let mut output = Self::new(context);
        let result = output.print_output_impl(writable);
        result.map(|()| output.buf)
    }

    fn print_output_impl<W>(&mut self, writable: &W) -> Result<(), Err>
    where
        W: Writable<Self>,
    {
        let future = pin!(writable.write_to(self));
        match future.poll(&mut std::task::Context::from_waker(Waker::noop())) {
            Poll::Pending => panic!("Expected a complete future"),
            Poll::Ready(result) => result,
        }
    }
}

impl<Ctx> InMemoryOutput<Ctx>
where
    Ctx: Context,
{
    /// Gets the string output of a single writable.
    ///
    /// Infallible version of [Self::try_print_output]. See that function's documentation for
    /// full details.
    ///
    /// **Panics** if the writable returns a pending future (particularly, this may happen if
    /// a writable introduces its own async computations that do not come from the output)
    pub fn print_output<W>(context: Ctx, writable: &W) -> String
    where
        W: Writable<Self>,
    {
        Self::try_print_output(context, writable).unwrap_or_else(|e| match e {})
    }
}

/// Turns a [WritableSeq] into an iterator over owned strings.
///
/// The iterator implementation calls [InMemoryOutput::try_print_output] for each writable produced
/// by the sequence. It uses Rust's async mechanics in order to invert control flow and produce
/// lazy iteration, making sure to return complete futures from the [crate::SequenceAccept] when the
/// iterator is ready to advance. However, this type expects a monopoly on such async control
/// flow and may panic if extraneous async waiting is introduced.
///
/// Accordingly, this type is intended mainly for testing purposes, allowing the caller to check
/// the output of their [WritableSeq] implementations.
///
/// ### Iteration and Errors
///
/// The default error type is no error (infallible). However, the caller can specify a different
/// error type in accordance with [InMemoryOutput].
///
/// If any of the writable values produces an error, it is returned instead of the string for
/// that item in the iterator. However, if the sequence itself produces an error, then the iterator
/// will produce an error as its final item and stop.
///
/// ### Panics
///
/// Iteration may panic if the sequence or any of its writable outputs returns a future that
/// yields a pending poll based on external async computations (in particular, only pending polls
/// caused by the iterative backpressure emitted from the [crate::SequenceAccept] implementation are
/// allowed)
///
pub struct IntoStringIter<Ctx, Seq, Err = Infallible> {
    context: Ctx,
    sequence: Seq,
    error_type: PhantomData<fn(Infallible) -> Err>,
}

impl<Ctx, Seq, Err> IntoStringIter<Ctx, Seq, Err> {
    pub fn new(context: Ctx, sequence: Seq) -> Self {
        Self {
            context,
            sequence,
            error_type: PhantomData,
        }
    }
}

impl<Ctx, Seq, Err> Clone for IntoStringIter<Ctx, Seq, Err>
where
    Ctx: Clone,
    Seq: Clone,
{
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            sequence: self.sequence.clone(),
            error_type: PhantomData,
        }
    }
}

impl<Ctx, Seq, Err> Debug for IntoStringIter<Ctx, Seq, Err>
where
    Ctx: Debug,
    Seq: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IntoStringIter")
            .field("context", &self.context)
            .field("sequence", &self.sequence)
            .field("error_type", &std::any::type_name::<Err>())
            .finish()
    }
}

impl<Ctx, Seq, Err> IntoIterator for IntoStringIter<Ctx, Seq, Err>
where
    Ctx: Context,
    Seq: WritableSeq<InMemoryOutput<Ctx, Err>>,
    Err: From<Infallible>,
{
    type Item = Result<String, Err>;
    type IntoIter = ToStringIter<Ctx, Seq, Err>;
    fn into_iter(self) -> Self::IntoIter {
        ToStringIter(string_iter::StringIter::new(self.context, self.sequence))
    }
}

/// The iterator produced by [IntoStringIter].
pub struct ToStringIter<Ctx, Seq, Err = Infallible>(string_iter::StringIter<Ctx, Seq, Err>);

impl<Ctx, Seq, Err> Debug for ToStringIter<Ctx, Seq, Err>
where
    Err: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToStringIter")
            .field("inner", &self.0)
            .finish()
    }
}

impl<Ctx, Seq, Err> Iterator for ToStringIter<Ctx, Seq, Err>
where
    Ctx: Context,
    Seq: WritableSeq<InMemoryOutput<Ctx, Err>>,
    Err: From<Infallible>,
{
    type Item = Result<String, Err>;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

mod string_iter {
    use crate::context::Context;
    use crate::util::InMemoryOutput;
    use crate::{SequenceAccept, Writable, WritableSeq};
    use std::cell::Cell;
    use std::convert::Infallible;
    use std::fmt::Debug;
    use std::future::poll_fn;
    use std::mem::{ManuallyDrop, MaybeUninit};
    use std::ops::DerefMut;
    use std::pin::Pin;
    use std::ptr::NonNull;
    use std::task::{Poll, Waker};
    use std::{mem, ptr};

    pub struct StringIter<Ctx, Seq, Err> {
        progressor: NonNull<Progressor<Ctx, Seq, Err>>,
        // If the sequence produced an error, sometimes we keep it until next() is called again
        // If Err = Infallible, a good compiler will optimize this field away
        seq_error_in_pipe: Option<Err>,
        finished: bool,
    }

    impl<Ctx, Seq, Err> Debug for StringIter<Ctx, Seq, Err>
    where
        Err: Debug,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let progressor = self.progressor.as_ptr();
            let buffer = unsafe {
                // SAFETY
                // This value can be read from multiple places
                &*(&raw const (*progressor).buffer)
            };
            f.debug_struct("StringIter")
                .field(
                    "marker",
                    &(&std::any::type_name::<Ctx>(), &std::any::type_name::<Seq>()),
                )
                .field("progressor.buffer", buffer)
                .field("seq_error_in_pipe", &self.seq_error_in_pipe)
                .field("finished", &self.finished)
                .finish()
        }
    }

    impl<Ctx, Seq, Err> Drop for StringIter<Ctx, Seq, Err> {
        fn drop(&mut self) {
            Progressor::deallocate(self.progressor)
        }
    }

    type Progressor<Ctx, Seq, Err> =
        RawProgressor<Ctx, Seq, Err, dyn Future<Output = Result<(), Err>>>;

    // A self-referential struct and DST.
    // We initialize it field-by-field, allowing us to use pointers to other parts
    // Once ready, we coerce to dyn Future to make this an unsized type
    struct RawProgressor<Ctx, Seq, Err, Fut: ?Sized> {
        // The one-item buffer is shared inside and outside the future
        buffer: ItemBuffer<Err>,
        // The storage for the context and sequence
        // Not to be touched! Fut takes permanent (mutable) references to what's inside
        vault: RawProgressorVault<Ctx, Seq, Err>,
        // DST-capable future. Contains references to:
        // 1. acceptor: &mut
        // 2. sequence: &
        // 3. buffer: *const (via acceptor)

        // This doesn't need to be ManuallyDrop if we can drop via pointer
        // Can remove this once #![feature(layout_for_ptr)] is stable
        future: ManuallyDrop<Fut>,
    }

    struct RawProgressorVault<Ctx, Seq, Err> {
        // Fut takes a permanent mutable reference to this field
        acceptor: SeqAccept<Ctx, Err>,
        // Also used by Fut, but immutable
        sequence: Seq,
    }

    impl<Ctx, Seq, Err> StringIter<Ctx, Seq, Err>
    where
        Ctx: Context,
        Seq: WritableSeq<InMemoryOutput<Ctx, Err>>,
        Err: From<Infallible>,
    {
        pub fn new(context: Ctx, sequence: Seq) -> Self {
            let ptr = Self::make_raw_progressor(context, sequence, |vault| {
                WritableSeq::for_each(&vault.sequence, &mut vault.acceptor)
            });
            Self {
                progressor: ptr,
                seq_error_in_pipe: None,
                finished: false,
            }
        }

        // Why use the following function

        // 1. Generic Inference
        // We need this function to allow generics to be inferred
        // Inference lets us work around WritableSeq::for_each returning an anonymous future

        // 2. Lifetime Hack
        // Although we know that Ctx, Seq outlive Self, the borrow checker often bitches about it
        // So, this function gets rid of that limitation.
        fn make_raw_progressor<'f, MakeFut, Fut>(
            context: Ctx,
            sequence: Seq,
            make_fut: MakeFut,
        ) -> NonNull<Progressor<Ctx, Seq, Err>>
        where
            Fut: Future<Output = Result<(), Err>> + 'f,
            MakeFut: FnOnce(&'f mut RawProgressorVault<Ctx, Seq, Err>) -> Fut,
            Ctx: 'f,
            Seq: 'f,
            Err: 'f,
        {
            // First, allocate the whole RawProgressor onto the heap
            // This will allow us to use stable pointers everywhere (pinning, effectively)
            let allocated = Box::new(MaybeUninit::<RawProgressor<Ctx, Seq, Err, Fut>>::uninit());
            unsafe {
                // SAFETY
                // Initialize fields one-by-one
                // All of our pointers will be stable, because we put everything in a box
                let fields_ptr = Box::into_raw(allocated);
                let fields_ptr = (&mut *fields_ptr).as_mut_ptr();

                // We initialize the buffer here, then re-use the pointer later
                let buffer_ptr = &raw mut (*fields_ptr).buffer;
                ptr::write(buffer_ptr, ItemBuffer::default());

                // We initialize acceptor using the stable buffer pointer
                // We initialize sequence as passed
                let vault_ptr = &raw mut (*fields_ptr).vault;
                ptr::write(
                    vault_ptr,
                    RawProgressorVault {
                        acceptor: SeqAccept {
                            output: InMemoryOutput::new(context),
                            buffer: buffer_ptr,
                        },
                        sequence,
                    },
                );

                // Initialize future: uses sequence + acceptor
                let future_ptr = &raw mut (*fields_ptr).future;
                ptr::write(future_ptr, ManuallyDrop::new(make_fut(&mut *vault_ptr)));

                // Fully initialized!
                // This lifetime cast is safe because Ctx and Seq outlive the future
                let fields_ptr = mem::transmute::<
                    *mut RawProgressor<_, _, _, dyn Future<Output = Result<(), Err>> + 'f>,
                    *mut RawProgressor<_, _, _, dyn Future<Output = Result<(), Err>> + 'static>,
                >(fields_ptr);
                NonNull::<Progressor<Ctx, Seq, Err>>::new_unchecked(fields_ptr)
            }
        }
    }

    impl<Ctx, Seq, Err> Progressor<Ctx, Seq, Err> {
        fn deallocate(ptr: NonNull<Self>) {
            let ptr = ptr.as_ptr();
            unsafe {
                // SAFETY
                // We perform an orderly drop and de-allocation, starting with the future
                {
                    let future_ptr = &raw mut (*ptr).future;
                    let future_to_drop = &mut *future_ptr;
                    ManuallyDrop::drop(future_to_drop);
                }
                let _allocation = Box::from_raw(ptr);
            }
        }
    }

    impl<Ctx, Seq, Err> Iterator for StringIter<Ctx, Seq, Err> {
        type Item = Result<String, Err>;
        fn next(&mut self) -> Option<Self::Item> {
            if self.finished {
                return None;
            }
            // Check for errors from the previous call
            if let Some(error) = mem::take(&mut self.seq_error_in_pipe) {
                self.finished = true;
                return Some(Err(error));
            }
            let fields_ptr = self.progressor.as_ptr();
            let (poll_outcome, item) = unsafe {
                // SAFETY
                // First poll the future
                // We know the future is pinned because it is heap-allocated
                let future_ptr = &raw mut (*fields_ptr).future;
                let pinned_future = Pin::new_unchecked((&mut *future_ptr).deref_mut());

                // Poll the future: can fill the buffer
                let poll_outcome =
                    pinned_future.poll(&mut std::task::Context::from_waker(Waker::noop()));

                // We can now use the buffer freely
                let buffer_ptr = &raw const (*fields_ptr).buffer;
                let item = (&*buffer_ptr).extract();

                (poll_outcome, item)
            };
            match poll_outcome {
                Poll::Pending => {
                    // The future stalling tells us that there is an item in the buffer
                    // So, this should always be Some
                    assert!(
                        item.is_some(),
                        "Extraneous async computations (writable should complete regularly)"
                    );
                }
                Poll::Ready(Err(seq_error)) => {
                    // The sequence itself threw an error
                    // Check whether any Writable was sent to the sequence
                    if item.is_some() {
                        // The sequence produced an item, then returned an error
                        // Store that error and return it in the next round
                        self.seq_error_in_pipe = Some(seq_error);
                    } else {
                        // No item, but everything's done
                        self.finished = true;
                        return Some(Err(seq_error));
                    }
                }
                Poll::Ready(Ok(())) => {
                    // All done!
                    self.finished = true;
                    // item can be None if we are fully empty
                }
            };
            item
        }
    }

    struct SeqAccept<Ctx, Err> {
        output: InMemoryOutput<Ctx, Err>,
        buffer: *const ItemBuffer<Err>,
    }

    impl<Ctx, Err> SequenceAccept<InMemoryOutput<Ctx, Err>> for SeqAccept<Ctx, Err>
    where
        Ctx: Context,
        Err: From<Infallible>,
    {
        async fn accept<W>(&mut self, writable: &W) -> Result<(), Err>
        where
            W: Writable<InMemoryOutput<Ctx, Err>>,
        {
            poll_fn(|_| {
                let buffer = unsafe {
                    // SAFETY
                    // We touch this buffer in one other place, outside the future
                    &*self.buffer
                };
                if !buffer.has_space() {
                    return Poll::Pending;
                }
                let result = self.output.print_output_impl(writable);
                let string = mem::take(&mut self.output.buf);
                buffer.set_new(result.map(|()| string));
                Poll::Ready(Ok(()))
            })
            .await
        }
    }

    struct ItemBuffer<Err>(Cell<Option<Result<String, Err>>>);

    impl<Err> Default for ItemBuffer<Err> {
        fn default() -> Self {
            Self(Cell::new(None))
        }
    }

    impl<Err> ItemBuffer<Err> {
        fn inspect<F, R>(&self, op: F) -> R
        where
            F: FnOnce(&Option<Result<String, Err>>) -> R,
        {
            let current = self.0.take();
            let result = op(&current);
            self.0.set(current);
            result
        }
    }

    impl<Err> Debug for ItemBuffer<Err>
    where
        Err: Debug,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            self.inspect(|current| {
                f.debug_struct("ItemBuffer")
                    .field("current", current)
                    .finish()
            })
        }
    }

    impl<Err> ItemBuffer<Err> {
        fn has_space(&self) -> bool {
            self.inspect(Option::is_none)
        }

        fn set_new(&self, value: Result<String, Err>) {
            self.0.set(Some(value));
        }

        fn extract(&self) -> Option<Result<String, Err>> {
            self.0.take()
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::common::{CombinedSeq, NoOpSeq, SingularSeq, Str, StrArrSeq};
    use crate::context::EmptyContext;
    use crate::util::IntoStringIter;
    use crate::{Output, SequenceAccept, Writable, WritableSeq};
    use std::convert::Infallible;

    #[test]
    fn sequence_iterator() {
        let sequence = StrArrSeq(&["One", "Two", "Three"]);
        let iterator = IntoStringIter::new(EmptyContext, sequence);
        let iterator = iterator.into_iter();
        let expected = &["One", "Two", "Three"].map(|s| Ok::<_, Infallible>(String::from(s)));
        assert_eq!(iterator.collect::<Vec<_>>(), Vec::from(expected));
    }

    #[test]
    fn sequence_iterator_empty() {
        let sequence = NoOpSeq;
        let iterator: IntoStringIter<_, _> = IntoStringIter::new(EmptyContext, sequence);
        let iterator = iterator.into_iter();
        assert!(iterator.collect::<Vec<_>>().is_empty());
    }

    #[derive(Clone)]
    struct SequenceWithError<Seq> {
        emit_before: bool,
        seq: Seq,
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct SampleError;

    // Warning: In future rust versions this will be automatically implemented
    impl From<Infallible> for SampleError {
        fn from(value: Infallible) -> Self {
            match value {}
        }
    }

    impl<O, Seq> WritableSeq<O> for SequenceWithError<Seq>
    where
        O: Output<Error = SampleError>,
        Seq: WritableSeq<O>,
    {
        async fn for_each<S>(&self, sink: &mut S) -> Result<(), O::Error>
        where
            S: SequenceAccept<O>,
        {
            if !self.emit_before {
                self.seq.for_each(sink).await?;
            }
            Err(SampleError)
        }
    }

    #[test]
    fn sequence_iterator_seq_error() {
        let sequence = SequenceWithError {
            emit_before: true,
            seq: StrArrSeq(&["Will", "Never", "Be", "Seen"]),
        };
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(Some(Err(SampleError)), iterator.clone().into_iter().next());
        assert!(iterator.into_iter().find(Result::is_ok).is_none());
    }

    #[test]
    fn sequence_iterator_seq_error_afterward() {
        let sequence = SequenceWithError {
            emit_before: false,
            seq: StrArrSeq(&["Data", "More"]),
        };
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(
            vec![
                Ok(String::from("Data")),
                Ok(String::from("More")),
                Err(SampleError)
            ],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn sequence_iterator_seq_error_in_between() {
        let sequence = CombinedSeq(
            StrArrSeq(&["One", "Two"]),
            SequenceWithError {
                emit_before: true,
                seq: SingularSeq(Str("Final")),
            },
        );
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(
            vec![
                Ok(String::from("One")),
                Ok(String::from("Two")),
                Err(SampleError)
            ],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn sequence_iterator_seq_error_empty() {
        let sequence = SequenceWithError {
            emit_before: true,
            seq: NoOpSeq,
        };
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(
            vec![Err(SampleError)],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }

    #[derive(Clone, Debug)]
    struct ProduceError;

    impl<O> Writable<O> for ProduceError
    where
        O: Output<Error = SampleError>,
    {
        async fn write_to(&self, _: &mut O) -> Result<(), O::Error> {
            Err(SampleError)
        }
    }

    #[test]
    fn sequence_iterator_write_error() {
        let sequence = CombinedSeq(SingularSeq(ProduceError), StrArrSeq(&["Is", "Seen"]));
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(Some(Err(SampleError)), iterator.clone().into_iter().next());
        assert_eq!(
            vec![
                Err(SampleError),
                Ok(String::from("Is")),
                Ok(String::from("Seen")),
            ],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn sequence_iterator_write_error_afterward() {
        let sequence = CombinedSeq(StrArrSeq(&["Data", "MoreData"]), SingularSeq(ProduceError));
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(
            vec![
                Ok(String::from("Data")),
                Ok(String::from("MoreData")),
                Err(SampleError)
            ],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn sequence_iterator_write_error_in_between() {
        let sequence = CombinedSeq(
            StrArrSeq(&["Data", "Adjacent"]),
            CombinedSeq(SingularSeq(ProduceError), SingularSeq(Str("Final"))),
        );
        let iterator = IntoStringIter::<_, _, SampleError>::new(EmptyContext, sequence);
        assert_eq!(
            vec![
                Ok(String::from("Data")),
                Ok(String::from("Adjacent")),
                Err(SampleError),
                Ok(String::from("Final"))
            ],
            iterator.into_iter().collect::<Vec<_>>()
        );
    }
}