qubit-codec 0.17.4

Core codec traits and buffer conversion primitives for Rust
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Buffered output driver that encodes values into units.

use core::fmt;
use std::collections::TryReserveError;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::result::Result as CoreResult;

use qubit_io::BufferedOutput;
use qubit_io::BufferedOutputRecovery;
use qubit_io::ByteOutput;
use qubit_io::Output;
use qubit_io::SeekableByteOutput;
use qubit_utils::SliceRange;
use qubit_utils::allocation_error;

use super::internal::capacity_error_to_invalid_data;
use super::internal::map_encode_value_result;
use super::internal::validate_encode_progress;
use crate::CapacityError;
use crate::Codec;
use crate::TranscodeEncodeErrorOf;
use crate::TranscodeEncoder;
use crate::TranscodeProgress;
use crate::TranscodeStatus;
use crate::Transcoder;
use crate::value::codec_value_lifecycle::encode_complete_value_into_reserved;
use crate::value::codec_value_lifecycle::max_complete_encode_units;

/// Encodes an [`Output`] value stream into an [`Output`] unit stream.
///
/// This type owns only the unit-level [`qubit_io::BufferedOutput`]. Callers
/// pass a [`crate::Codec`] and error mapper to each encode operation, which
/// lets one buffered output drive different encoders without nesting buffers or
/// storing codec-specific state in the buffer owner.
///
/// [`Self::flush`] only drains already buffered units. State-aware streaming
/// encoders can use [`Self::reset`], [`Self::transcode`], and [`Self::finish`]
/// explicitly.
///
/// Pending units should be flushed or recovered before this adapter is
/// dropped. Its wrapped buffer only makes a best-effort drain during drop,
/// skips that drain after an inner I/O panic, and ignores any output error.
///
/// # Type Parameters
///
/// * `O` - Wrapped unit output.
///
/// # Examples
///
/// ```
/// use core::convert::Infallible;
/// use core::num::NonZeroUsize;
/// use std::io::Cursor;
/// use qubit_codec::{Codec, CodecTranscodeEncoder, DecodeFailure, TranscodeEncodeOutput};
/// use qubit_codec::{TranscodeEncoder, TranscodeStatus};
///
/// struct ByteCodec;
/// impl Codec for ByteCodec {
///     type Value = u8;
///     type Unit = u8;
///     type DecodeError = Infallible;
///     type EncodeError = Infallible;
///     const MIN_UNITS_PER_VALUE: usize = 1;
///     const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
///     const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
///     unsafe fn decode(&mut self, input: &[u8], index: usize)
///         -> Result<(u8, NonZeroUsize), DecodeFailure<Infallible>> {
///         Ok((input[index], NonZeroUsize::MIN))
///     }
///     unsafe fn encode(&mut self, value: &u8, output: &mut [u8], index: usize)
///         -> Result<usize, Infallible> {
///         output[index] = *value;
///         Ok(1)
///     }
/// }
///
/// let mut encoder = CodecTranscodeEncoder::new(ByteCodec);
/// let mut output = TranscodeEncodeOutput::with_capacity(Cursor::new(Vec::new()), 8);
/// let mut map_error = |_| std::io::Error::other("encode error");
/// output.reset(&mut encoder, &mut map_error)?;
/// let values = [1_u8, 2, 3];
/// let mut offset = 0;
/// while offset < values.len() {
///     let progress = output.transcode_step(
///         &mut encoder, &mut map_error, &values, offset, values.len() - offset,
///     )?;
///     offset += progress.read();
///     if let TranscodeStatus::NeedOutput { required, .. } = progress.status() {
///         output.ensure_spare_capacity(required.get())?;
///     }
/// }
/// output.finish(&mut encoder, &mut map_error)?;
/// assert_eq!(output.inner().get_ref(), &[1, 2, 3]);
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// `finish` commits final units, drains the buffered output, and flushes the
/// wrapped sink. Use `finish_to_buffer` followed by `flush` when those steps
/// need to be controlled separately.
#[must_use = "flush or recover pending output before dropping the adapter"]
pub struct TranscodeEncodeOutput<O>
where
    O: Output,
    O::Item: Copy + Default,
{
    /// Owns the wrapped unit sink and pending encoded units awaiting delivery.
    output: BufferedOutput<O>,
}

impl<O> TranscodeEncodeOutput<O>
where
    O: Output,
    O::Item: Copy + Default,
{
    /// Creates an encoder output with the default unit buffer capacity.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit output written by this adapter.
    ///
    /// # Returns
    ///
    /// A new buffered encoder output.
    ///
    /// # Panics
    ///
    /// Panics if initializing the default buffer requires
    /// `O::Item::default()` or `O::Item::clone()` and either operation panics,
    /// or if the default backing length exceeds `Vec`'s supported capacity.
    pub fn new(inner: O) -> Self {
        Self {
            output: BufferedOutput::new(inner),
        }
    }

    /// Creates an encoder output with a unit buffer of at least `capacity`.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit output written by this adapter.
    /// * `capacity` - Requested internal unit buffer capacity.
    ///
    /// # Returns
    ///
    /// A new buffered encoder output.
    ///
    /// # Panics
    ///
    /// Panics if initializing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics, or if the requested
    /// backing length exceeds `Vec`'s supported capacity.
    pub fn with_capacity(inner: O, capacity: usize) -> Self {
        Self {
            output: BufferedOutput::with_capacity(inner, capacity),
        }
    }

    /// Creates an encoder output with a unit buffer of at least `capacity`.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit output written by this adapter.
    /// * `capacity` - Requested internal unit buffer capacity.
    ///
    /// # Returns
    ///
    /// A buffered adapter owning `inner` on success.
    ///
    /// # Errors
    ///
    /// Returns an allocation error when the requested buffer cannot be
    /// allocated.
    ///
    /// # Panics
    ///
    /// Panics if initializing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics. Allocation failures are
    /// returned as errors; panics from element initialization are not caught.
    pub fn try_with_capacity(inner: O, capacity: usize) -> CoreResult<Self, TryReserveError> {
        Ok(Self {
            output: BufferedOutput::try_with_capacity(inner, capacity)?,
        })
    }

    /// Returns a shared reference to the wrapped unit output.
    ///
    /// Pending units remain in this adapter's internal buffer and are not
    /// visible through the returned output until [`Self::flush`] succeeds.
    ///
    /// # Returns
    ///
    /// A shared reference to the wrapped unit output.
    #[must_use]
    #[inline]
    pub const fn inner(&self) -> &O {
        self.output.inner()
    }

    /// Returns the available capacity of the spare output buffer.
    ///
    /// # Returns
    ///
    /// The number of output units that can still be appended without flushing.
    #[must_use]
    #[inline]
    pub fn spare_capacity(&self) -> usize {
        self.output.spare_capacity()
    }

    /// Returns raw spare-buffer parts for the internal output buffer.
    ///
    /// # Returns
    ///
    /// The full backing storage, the spare start index, and the spare unit
    /// count.
    #[must_use]
    #[inline]
    pub fn spare_raw_parts_mut(&mut self) -> (&mut [O::Item], usize, usize) {
        self.output.spare_raw_parts_mut()
    }

    /// Marks `count` units from [`Self::spare_raw_parts_mut`] as written.
    ///
    /// # Parameters
    ///
    /// * `count` - Initialized units to commit from the spare window.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `count <= Self::spare_capacity()` and
    /// that the corresponding units in the returned spare slice have been
    /// initialized.
    #[inline]
    pub unsafe fn advance(&mut self, count: usize) {
        // SAFETY: The caller guarantees `count` and initialization invariants.
        unsafe { self.output.advance(count) }
    }

    /// Ensures that at least `count` spare units are available.
    ///
    /// # Parameters
    ///
    /// * `count` - Number of spare units required.
    ///
    /// # Errors
    ///
    /// Returns allocation errors mapped to [`ErrorKind::OutOfMemory`], or I/O
    /// errors from the wrapped output while delivering pending units.
    ///
    /// # Panics
    ///
    /// Panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    pub fn ensure_spare_capacity(&mut self, count: usize) -> Result<()> {
        self.output.try_reserve_capacity(count).map_err(allocation_error)?;
        self.output.ensure_spare_capacity(count)
    }

    /// Consumes this adapter without flushing the wrapped output.
    ///
    /// This method does not call [`Self::flush`] and performs no I/O. `Pending`
    /// units were not reported as written and may be retried. `Indeterminate`
    /// means an inner write panicked and may have produced an external prefix;
    /// do not replay it automatically.
    ///
    /// # Returns
    ///
    /// The wrapped output and pending or indeterminate units.
    #[must_use = "the returned output and recovery status must be handled"]
    #[inline]
    pub fn into_parts(self) -> (O, BufferedOutputRecovery<O::Item>) {
        self.output.into_parts()
    }

    /// Flushes buffered units without finishing any encoder stream.
    ///
    /// # Errors
    ///
    /// Returns errors from the wrapped output while flushing pending units.
    #[inline]
    pub fn flush(&mut self) -> Result<()> {
        self.output.flush()
    }

    /// Encodes one codec value into this buffered unit output.
    ///
    /// The method grows the persistent internal buffer when necessary, then
    /// writes the complete encoded value into its spare window.
    ///
    /// # Type Parameters
    ///
    /// * `C` - Codec producing the wrapped output unit type.
    /// * `M` - Mapper from codec errors into I/O errors.
    ///
    /// # Parameters
    ///
    /// * `codec` - Codec used for this single-value encode.
    /// * `value` - Value to encode.
    /// * `map_error` - Mapper for codec-domain encode errors.
    ///
    /// # Errors
    ///
    /// Returns I/O errors from the wrapped output, `InvalidInput` when the
    /// codec output bound overflows or the value is outside the codec domain,
    /// or the error returned by `map_error` for codec encode, reset, and finish
    /// failures. A mapped codec error is wrapped in
    /// [`crate::TranscodeDomainError`] so its reset, main, or finish phase
    /// remains available through the returned I/O error's source chain. The
    /// mapped error itself is retained as that wrapper's source, including any
    /// custom payload or OS error code.
    ///
    /// Capacity planning fails before the codec runs. Preparing the spare
    /// buffer can first deliver older pending units to the wrapped output; it
    /// is not a transaction boundary for the whole call. If reset, encode, or
    /// finish fails, the codec may already have changed state, but units
    /// written into this call's spare window are not committed to the
    /// adapter. Older pending units remain subject to the wrapped output's
    /// buffering contract, and units delivered while preparing capacity
    /// cannot be rolled back. A successful call commits the actual written
    /// count to pending output but does not flush the sink. Do not replay
    /// the value after an error unless the codec provides a recovery
    /// protocol; reset does not undo state changes or output already
    /// delivered.
    ///
    /// Callers that previously downcast the outer I/O error directly to their
    /// mapped payload should first downcast it to
    /// `TranscodeDomainError<std::io::Error>`, then inspect its `source()`.
    /// For mapped OS errors, `raw_os_error()` is available on that inner
    /// source.
    ///
    /// # Panics
    ///
    /// Panics when the codec violates its declared reset, value-width, or
    /// finish bounds, or when `encode` writes a length different from
    /// `encode_len` in the same reset state. Also panics if growing the buffer
    /// requires `O::Item::default()` or `O::Item::clone()` and either
    /// operation panics.
    pub fn write_encoded_with<C, M>(&mut self, codec: &mut C, value: &C::Value, mut map_error: M) -> Result<()>
    where
        C: Codec<Unit = O::Item>,
        M: FnMut(C::EncodeError) -> Error,
    {
        let max_units = map_encode_value_result(
            max_complete_encode_units::<C>().map_err(TranscodeEncodeErrorOf::<C>::from),
            &mut map_error,
        )?;
        self.ensure_spare_capacity(max_units)?;
        let (units, output_index, available) = self.output.spare_raw_parts_mut();
        debug_assert!(
            available >= max_units,
            "reserved spare buffer is smaller than codec upper bound",
        );
        let written = map_encode_value_result(
            encode_complete_value_into_reserved(codec, value, units, output_index, max_units),
            &mut map_error,
        )?;
        // SAFETY: The spare buffer has the conservative complete lifecycle
        // capacity, and the helper reports how many initialized units it
        // actually wrote.
        unsafe {
            self.output.advance(written);
        }
        Ok(())
    }

    /// Runs encoder reset and buffers any stream-prefix units.
    ///
    /// This method reserves enough persistent buffer capacity for all reset
    /// output before calling `encoder`. Preparing that space may deliver
    /// previously buffered units to the wrapped output and can return an I/O
    /// error before `encoder.reset` runs. This delivery does not call the
    /// wrapped output's `flush` method.
    ///
    /// # Type Parameters
    ///
    /// * `E` - Transcoder producing the wrapped output unit type.
    /// * `M` - Mapper from transcoder errors into I/O errors.
    /// * `Value` - Source value type accepted by the transcoder.
    ///
    /// # Parameters
    ///
    /// * `encoder` - Transcoder whose stream prefix is being collected.
    /// * `map_error` - Mapper for reset failures.
    ///
    /// # Errors
    ///
    /// Returns capacity errors, allocation errors, or reset errors mapped by
    /// `map_error`.
    ///
    /// # Panics
    ///
    /// Panics when `encoder` writes more than its declared reset bound.
    /// Also panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    pub fn reset<E, M, Value>(&mut self, encoder: &mut E, map_error: &mut M) -> Result<()>
    where
        E: Transcoder<Input = Value, Output = O::Item>,
        M: FnMut(E::Error) -> Error,
    {
        let required = encoder.max_reset_output_len().map_err(capacity_error_to_invalid_data)?;
        self.ensure_spare_capacity(required)?;
        let (units, output_index, available) = self.output.spare_raw_parts_mut();
        debug_assert!(
            available >= required,
            "insufficient reset capacity reserved in spare output buffer",
        );
        let written = encoder.reset(units, output_index).map_err(&mut *map_error)?;
        assert!(written <= required, "reset wrote beyond its bound");
        // SAFETY: The encoder reported initialized units within the spare
        // range reserved above.
        unsafe {
            self.output.advance(written);
        }
        Ok(())
    }

    /// Encodes at most one step of the selected input range.
    ///
    /// Unlike [`Self::transcode`], this method does not reserve output space
    /// for the entire range and calls the encoder exactly once. The returned
    /// progress is relative to this call's input and output windows. Advance
    /// the input index by [`TranscodeProgress::read`]; if the status is
    /// `NeedOutput`, provide the requested spare capacity before retrying.
    /// Written units have already been committed to this adapter's pending
    /// buffer and must not be advanced again. A zero count validates the range
    /// and returns complete progress without delivering pending units or
    /// calling the encoder.
    ///
    /// # Type Parameters
    ///
    /// * `E` - Encoder producing the wrapped output unit type.
    /// * `M` - Mapper from encoder errors into I/O errors.
    /// * `Value` - Source value type accepted by the encoder.
    ///
    /// # Parameters
    ///
    /// * `encoder` - Encoder that processes one progress step.
    /// * `map_error` - Maps encoder errors to I/O errors.
    /// * `input` - Source values.
    /// * `input_index` - Start index inside `input`.
    /// * `count` - Number of values available from `input_index`.
    ///
    /// # Returns
    ///
    /// Progress for the single encoder call, including consumed input,
    /// committed output, and whether more output capacity is needed.
    ///
    /// # Errors
    ///
    /// Returns invalid input ranges, capacity, encoder, or output errors. An
    /// invalid encoder progress report is returned as `ErrorKind::InvalidData`.
    /// An error does not provide general transactional rollback or complete
    /// progress. The encoder may already have advanced, but units written by
    /// its failing call are not committed to this adapter's pending output.
    /// Do not replay the original input range without an encoder-specific
    /// recovery protocol. Earlier pending units retain the wrapped output's
    /// recovery contract; reset starts a new logical stream and does not undo
    /// output already delivered.
    ///
    /// # Panics
    ///
    /// Panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    ///
    /// # use core::convert::Infallible;
    /// # use core::num::NonZeroUsize;
    /// # use qubit_codec::Codec;
    /// # use qubit_codec::CodecTranscodeEncoder;
    /// # use qubit_codec::DecodeFailure;
    /// use qubit_codec::TranscodeEncodeOutput;
    /// use qubit_codec::TranscodeEncoder;
    /// use qubit_codec::TranscodeStatus;
    ///
    /// # struct ByteCodec;
    /// # impl Codec for ByteCodec {
    /// #     type Value = u8;
    /// #     type Unit = u8;
    /// #     type DecodeError = Infallible;
    /// #     type EncodeError = Infallible;
    /// #     const MIN_UNITS_PER_VALUE: usize = 1;
    /// #     const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
    /// #     const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
    /// #     unsafe fn decode(
    /// #         &mut self,
    /// #         input: &[u8],
    /// #         index: usize,
    /// #     ) -> Result<(u8, NonZeroUsize), DecodeFailure<Infallible>> {
    /// #         Ok((input[index], NonZeroUsize::MIN))
    /// #     }
    /// #     unsafe fn encode(
    /// #         &mut self,
    /// #         value: &u8,
    /// #         output: &mut [u8],
    /// #         index: usize,
    /// #     ) -> Result<usize, Infallible> {
    /// #         output[index] = *value;
    /// #         Ok(1)
    /// #     }
    /// # }
    /// fn encode<E>(encoder: &mut E, values: &[E::Input]) -> std::io::Result<Vec<u8>>
    /// where
    ///     E: TranscodeEncoder<Output = u8>,
    /// {
    ///     let mut output = TranscodeEncodeOutput::with_capacity(Cursor::new(Vec::new()), 8);
    ///     let mut map_error = |_| std::io::Error::other("encode error");
    ///     output.reset(encoder, &mut map_error)?;
    ///     let mut offset = 0;
    ///     while offset < values.len() {
    ///         let progress = output.transcode_step(
    ///             encoder,
    ///             &mut map_error,
    ///             values,
    ///             offset,
    ///             values.len() - offset,
    ///         )?;
    ///         offset += progress.read();
    ///         if let TranscodeStatus::NeedOutput { required, .. } = progress.status() {
    ///             output.ensure_spare_capacity(required.get())?;
    ///         }
    ///     }
    ///     output.finish(encoder, &mut map_error)?;
    ///     let (cursor, _) = output.into_parts();
    ///     Ok(cursor.into_inner())
    /// }
    ///
    /// let mut encoder = CodecTranscodeEncoder::new(ByteCodec);
    /// assert_eq!(encode(&mut encoder, &[1, 2, 3]).unwrap(), vec![1, 2, 3]);
    /// let mut empty_encoder = CodecTranscodeEncoder::new(ByteCodec);
    /// assert_eq!(encode(&mut empty_encoder, &[]).unwrap(), Vec::<u8>::new());
    /// ```
    pub fn transcode_step<E, M, Value>(
        &mut self,
        encoder: &mut E,
        map_error: &mut M,
        input: &[Value],
        input_index: usize,
        count: usize,
    ) -> Result<TranscodeProgress>
    where
        E: TranscodeEncoder<Input = Value, Output = O::Item>,
        M: FnMut(E::Error) -> Error,
    {
        let input_end = SliceRange::checked_range_end(
            input.len(),
            input_index,
            count,
            "encode input range exceeds source buffer",
        )?;
        if count == 0 {
            return Ok(TranscodeProgress::complete(0, 0));
        }
        let required = encoder
            .max_transcode_output_len(1)
            .map_err(capacity_error_to_invalid_data)?
            .max(1);
        self.ensure_spare_capacity(required)?;
        let (units, output_index, available_output) = self.output.spare_raw_parts_mut();
        let progress = encoder
            .transcode(&input[..input_end], input_index, units, output_index)
            .map_err(&mut *map_error)?;
        let progress = validate_encode_progress(progress, input_index, count, output_index, available_output)?;
        // SAFETY: Validated progress fits the spare output window.
        unsafe {
            self.output.advance(progress.written());
        }
        Ok(progress)
    }

    /// Encodes values from an indexed input range using a streaming
    /// [`Transcoder`].
    ///
    /// This streaming path reserves the encoder's conservative output bound
    /// for the whole batch before calling it. Preparing that space may deliver
    /// previously buffered units to the wrapped output and can return an I/O
    /// error before consuming source values. Split large batches into smaller
    /// calls when you need to limit the memory required for one operation.
    ///
    /// # Type Parameters
    ///
    /// * `E` - Encoder producing the wrapped output unit type.
    /// * `M` - Mapper from encoder errors into I/O errors.
    /// * `Value` - Source value type accepted by the encoder.
    ///
    /// # Parameters
    ///
    /// * `encoder` - Streaming encoder used for this operation.
    /// * `map_error` - Function mapping transcode errors into I/O errors.
    /// * `input` - Source values.
    /// * `input_index` - Start index inside `input`.
    /// * `count` - Maximum number of values to encode.
    ///
    /// # Returns
    ///
    /// The number of source values consumed.
    ///
    /// # Errors
    ///
    /// Returns invalid input ranges, capacity, transcode, or output errors. An
    /// output-bound contract violation is reported as `ErrorKind::InvalidData`.
    /// An error does not provide general transactional rollback or complete
    /// progress. The encoder may already have advanced, while units written by
    /// its failing call are not committed to this adapter's pending output.
    /// Do not replay the original input range unless the concrete encoder
    /// provides an explicit recovery protocol. Previously committed pending
    /// output remains subject to the wrapped output's recovery contract, and
    /// reset starts a new logical stream without undoing output already
    /// delivered.
    ///
    /// # Panics
    ///
    /// Panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    ///
    /// # Examples
    ///
    /// A value that only implements [`Transcoder`] is not an encoder and cannot
    /// be passed to this method.
    ///
    /// ```compile_fail
    /// use std::io::Error;
    /// use std::io::sink;
    ///
    /// use qubit_codec::CapacityError;
    /// use qubit_codec::TranscodeEncodeError;
    /// use qubit_codec::TranscodeEncodeOutput;
    /// use qubit_codec::TranscodeProgress;
    /// use qubit_codec::Transcoder;
    ///
    /// struct GenericTranscoder;
    ///
    /// impl Transcoder for GenericTranscoder {
    ///     type Input = u8;
    ///     type Output = u8;
    ///     type Error = TranscodeEncodeError<(), u8>;
    ///
    ///     fn max_transcode_output_len(
    ///         &self,
    ///         input_len: usize,
    ///     ) -> Result<usize, CapacityError> {
    ///         Ok(input_len)
    ///     }
    ///
    ///     fn reset(
    ///         &mut self,
    ///         _output: &mut [u8],
    ///         _output_index: usize,
    ///     ) -> Result<usize, Self::Error> {
    ///         Ok(0)
    ///     }
    ///
    ///     fn transcode(
    ///         &mut self,
    ///         input: &[u8],
    ///         input_index: usize,
    ///         _output: &mut [u8],
    ///         _output_index: usize,
    ///     ) -> Result<TranscodeProgress, Self::Error> {
    ///         Ok(TranscodeProgress::complete(input.len() - input_index, 0))
    ///     }
    ///
    ///     fn finish(
    ///         &mut self,
    ///         _output: &mut [u8],
    ///         _output_index: usize,
    ///     ) -> Result<usize, Self::Error> {
    ///         Ok(0)
    ///     }
    /// }
    ///
    /// let mut output = TranscodeEncodeOutput::with_capacity(sink(), 1);
    /// let mut transcoder = GenericTranscoder;
    /// let mut map_error = |_| Error::other("transcode error");
    /// let _ = output.transcode(
    ///     &mut transcoder,
    ///     &mut map_error,
    ///     &[0_u8],
    ///     0,
    ///     1,
    /// );
    /// ```
    pub fn transcode<E, M, Value>(
        &mut self,
        encoder: &mut E,
        map_error: &mut M,
        input: &[Value],
        input_index: usize,
        count: usize,
    ) -> Result<usize>
    where
        E: TranscodeEncoder<Input = Value, Output = O::Item>,
        M: FnMut(E::Error) -> Error,
    {
        let input_end = SliceRange::checked_range_end(
            input.len(),
            input_index,
            count,
            "encode input range exceeds source buffer",
        )?;
        if count == 0 {
            return Ok(0);
        }
        let required = encoder
            .max_transcode_output_len(count)
            .map_err(capacity_error_to_invalid_data)?
            .max(1);
        self.ensure_spare_capacity(required)?;
        let input = &input[..input_end];
        let mut read_total = 0;
        while read_total < count {
            let (units, output_index, available_output) = self.output.spare_raw_parts_mut();
            let remaining_input = count - read_total;
            let progress = encoder
                .transcode(input, input_index + read_total, units, output_index)
                .map_err(&mut *map_error)?;
            let progress = validate_encode_progress(
                progress,
                input_index + read_total,
                remaining_input,
                output_index,
                available_output,
            )?;
            let read = progress.read();
            let written = progress.written();
            // SAFETY: The progress bounds check above proved that the encoder
            // initialized no more than the available spare output window.
            unsafe {
                self.output.advance(written);
            }
            read_total += read;
            if progress.is_complete() {
                return Ok(read_total);
            }
            if let TranscodeStatus::NeedOutput { required, .. } = progress.status()
                && (read_total == count || available_output - written < required.get() || (read == 0 && written == 0))
            {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "encoder output bound was insufficient",
                ));
            }
        }
        Ok(read_total)
    }

    /// Finishes the encoder and flushes the wrapped unit output.
    ///
    /// This method writes final units directly into the internal spare buffer,
    /// growing it when [`Transcoder::max_finish_output_len`] exceeds the
    /// current capacity.
    ///
    /// # Type Parameters
    ///
    /// * `E` - Transcoder producing the wrapped output unit type.
    /// * `M` - Mapper from transcoder errors into I/O errors.
    /// * `Value` - Source value type accepted by the transcoder.
    ///
    /// # Parameters
    ///
    /// * `encoder` - Encoder whose final units are being collected.
    /// * `map_error` - Function mapping transcode errors into I/O errors.
    ///
    /// # Errors
    ///
    /// Returns capacity, transcode finalization, or wrapped output flush
    /// errors.
    ///
    /// # Panics
    ///
    /// Panics when the encoder exceeds its declared finish-output bound.
    /// Also panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    pub fn finish<E, M, Value>(&mut self, encoder: &mut E, map_error: &mut M) -> Result<()>
    where
        E: Transcoder<Input = Value, Output = O::Item>,
        M: FnMut(E::Error) -> Error,
    {
        self.finish_to_buffer(encoder, map_error)?;
        self.output.flush()
    }

    /// Finishes the encoder while retaining final units in the output buffer.
    ///
    /// This method separates encoder finalization from output delivery. It is
    /// useful when a caller must record successful finalization before a later
    /// flush can fail. Call [`Self::flush`] to deliver the retained units.
    ///
    /// # Type Parameters
    ///
    /// * `E` - Transcoder producing the wrapped output unit type.
    /// * `M` - Mapper from transcoder errors into I/O errors.
    /// * `Value` - Source value type accepted by the transcoder.
    ///
    /// # Parameters
    ///
    /// * `encoder` - Encoder whose final units are being collected.
    /// * `map_error` - Function mapping transcode errors into I/O errors.
    ///
    /// # Errors
    ///
    /// Returns capacity planning, allocation, or transcoder finalization
    /// errors. It does not perform output I/O; use [`Self::finish`] to deliver
    /// the buffered final units and flush the wrapped output.
    ///
    /// # Panics
    ///
    /// Panics when `encoder` writes more units than its declared finish bound.
    /// Also panics if growing the buffer requires `O::Item::default()` or
    /// `O::Item::clone()` and either operation panics.
    pub fn finish_to_buffer<E, M, Value>(&mut self, encoder: &mut E, map_error: &mut M) -> Result<()>
    where
        E: Transcoder<Input = Value, Output = O::Item>,
        M: FnMut(E::Error) -> Error,
    {
        let required = match encoder.max_finish_output_len() {
            Ok(required) => required,
            Err(error) => return Err(capacity_error_to_invalid_data(error)),
        };
        let pending = self.output.capacity() - self.output.spare_capacity();
        let capacity = pending
            .checked_add(required)
            .ok_or_else(|| capacity_error_to_invalid_data(CapacityError::OutputLengthOverflow))?;
        self.output.try_reserve_capacity(capacity).map_err(allocation_error)?;
        let (units, output_index, available) = self.output.spare_raw_parts_mut();
        debug_assert!(
            available >= required,
            "insufficient finish capacity reserved in spare output buffer",
        );
        let written = encoder.finish(units, output_index).map_err(&mut *map_error)?;
        assert!(written <= required, "finish wrote beyond its bound");
        // SAFETY: The encoder reported initialized units within the spare
        // range that was reserved above.
        unsafe {
            self.output.advance(written);
        }
        Ok(())
    }
}

impl<O> TranscodeEncodeOutput<O>
where
    O: SeekableByteOutput,
{
    /// Flushes pending bytes, then seeks the wrapped byte output.
    ///
    /// # Parameters
    ///
    /// * `position` - Target seek position.
    ///
    /// # Returns
    ///
    /// The new stream position reported by the wrapped output.
    ///
    /// # Errors
    ///
    /// Returns flush or seek errors from the wrapped output.
    #[inline]
    pub fn seek(&mut self, position: SeekFrom) -> Result<u64> {
        self.output.seek_to(position)
    }
}

impl<O> Write for TranscodeEncodeOutput<O>
where
    O: ByteOutput,
{
    /// Writes raw bytes through the internal buffer without encoding them.
    ///
    /// # Parameters
    ///
    /// * `input` - Bytes to append to the buffered unit output.
    ///
    /// # Returns
    ///
    /// The number of bytes accepted, which may be shorter than `input`.
    ///
    /// # Errors
    ///
    /// Propagates wrapped-output errors when buffer delivery is needed.
    #[inline]
    fn write(&mut self, input: &[u8]) -> Result<usize> {
        Output::write(&mut self.output, input)
    }

    /// Writes all raw bytes through the internal buffer without encoding them.
    ///
    /// # Parameters
    ///
    /// * `input` - Bytes that must all be accepted before success.
    ///
    /// # Errors
    ///
    /// Propagates output errors and returns `WriteZero` if output stops
    /// progressing.
    ///
    /// # Panics
    ///
    /// Panics when the wrapped output reports more bytes than supplied.
    fn write_all(&mut self, input: &[u8]) -> Result<()> {
        let mut written = 0;
        while written < input.len() {
            let count = match Output::write(&mut self.output, &input[written..]) {
                Ok(count) => count,
                Err(error) if error.kind() == ErrorKind::Interrupted => continue,
                Err(error) => return Err(error),
            };
            if count == 0 {
                return Err(Error::from(ErrorKind::WriteZero));
            }
            assert!(
                count <= input.len() - written,
                "Output::write returned a count beyond the input length",
            );
            written += count;
        }
        Ok(())
    }

    /// Flushes buffered bytes to the wrapped output without finishing an
    /// encoder.
    ///
    /// # Errors
    ///
    /// Propagates wrapped-output flush errors.
    #[inline]
    fn flush(&mut self) -> Result<()> {
        TranscodeEncodeOutput::flush(self)
    }
}

impl<O> Seek for TranscodeEncodeOutput<O>
where
    O: SeekableByteOutput,
{
    /// Flushes pending bytes, then seeks the wrapped byte output.
    ///
    /// # Parameters
    ///
    /// * `position` - Target position relative to the selected seek origin.
    ///
    /// # Returns
    ///
    /// The new absolute byte position.
    ///
    /// # Errors
    ///
    /// Propagates flush or seek errors from the wrapped output.
    #[inline]
    fn seek(&mut self, position: SeekFrom) -> Result<u64> {
        self.seek(position)
    }
}

impl<O> fmt::Debug for TranscodeEncodeOutput<O>
where
    O: Output,
    O::Item: Copy + Default,
    BufferedOutput<O>: fmt::Debug,
{
    /// Formats the owned buffer and underlying output for diagnostics.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Destination and formatting options.
    ///
    /// # Errors
    ///
    /// Returns a formatting error if the destination rejects output.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TranscodeEncodeOutput")
            .field("output", &self.output)
            .finish()
    }
}