qubit-codec 0.17.0

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
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Buffered input driver that decodes units into values.

use core::fmt::Debug;
use core::fmt::Formatter;
use core::fmt::Result as FormatResult;
use std::collections::TryReserveError;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Result;
use std::io::Seek;
use std::io::SeekFrom;
use std::result::Result as StdResult;

use qubit_io::Buffer;
use qubit_io::BufferedInput;
use qubit_io::ByteInput;
use qubit_io::Input;
use qubit_io::SeekableByteInput;
use qubit_utils::SliceRange;
use qubit_utils::UncheckedSlice;
use qubit_utils::allocation_error;

use super::internal::CodecDecodeDriver;
use super::transcode_progress_validation::validate_decode_progress;
use crate::CapacityError;
use crate::Codec;
use crate::DecodeLifecycleOutput;
use crate::DecodeLifecycleProgress;
use crate::TranscodeFailure;
use crate::TranscodeProgress;
use crate::TranscodeStatus;
use crate::Transcoder;
use crate::codec::assert_unit_bounds;

/// Decodes an [`Input`] unit stream into an [`Input`] value stream.
///
/// This type owns only the unit-level [`qubit_io::BufferedInput`]. Callers pass
/// a streaming [`Transcoder`] and error mapper to each decode operation, which
/// lets one buffered input drive different decoders without nesting buffers or
/// storing decoder-specific state in the buffer owner.
///
/// # Type Parameters
///
/// * `I` - Wrapped unit input.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use qubit_codec::TranscodeDecodeInput;
///
/// let input = TranscodeDecodeInput::with_capacity(Cursor::new(vec![1_u8]), 8);
/// assert!(input.unread_len() <= 8);
/// ```
pub struct TranscodeDecodeInput<I>
where
    I: Input,
    I::Item: Copy + Default,
{
    /// Owns the unit source and retains unread units across decode operations.
    input: BufferedInput<I>,
}

impl<I> TranscodeDecodeInput<I>
where
    I: Input,
    I::Item: Copy + Default,
{
    /// Creates a decoder input with the default unit buffer capacity.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit input read by this adapter.
    ///
    /// # Returns
    ///
    /// A new buffered decoder input.
    #[must_use]
    pub fn new(inner: I) -> Self {
        Self {
            input: BufferedInput::new(inner),
        }
    }

    /// Creates a decoder input with a unit buffer of at least `capacity`.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit input read by this adapter.
    /// * `capacity` - Requested internal unit buffer capacity.
    ///
    /// # Returns
    ///
    /// A new buffered decoder input.
    #[must_use]
    pub fn with_capacity(inner: I, capacity: usize) -> Self {
        Self {
            input: BufferedInput::with_capacity(inner, capacity),
        }
    }

    /// Creates a decoder input with a unit buffer of at least `capacity`.
    ///
    /// # Parameters
    ///
    /// * `inner` - Unit input read by this adapter.
    /// * `capacity` - Requested internal unit buffer capacity.
    ///
    /// # Returns
    ///
    /// Returns a buffered adapter owning `inner` with at least the requested
    /// capacity.
    ///
    /// # Errors
    ///
    /// Returns an allocation error when the requested buffer cannot be
    /// allocated.
    pub fn try_with_capacity(inner: I, capacity: usize) -> StdResult<Self, TryReserveError> {
        Ok(Self {
            input: BufferedInput::try_with_capacity(inner, capacity)?,
        })
    }

    /// Returns a shared reference to the wrapped unit input.
    ///
    /// The wrapped input can be physically positioned after units that remain
    /// unread in this adapter's internal buffer.
    ///
    /// # Returns
    ///
    /// A shared reference to the wrapped unit input.
    #[must_use]
    #[inline]
    pub const fn inner(&self) -> &I {
        self.input.inner()
    }

    /// Returns the number of unread units currently buffered.
    ///
    /// # Returns
    ///
    /// The number of unread units in the internal buffer.
    #[must_use]
    #[inline]
    pub fn unread_len(&self) -> usize {
        self.input.unread_len()
    }

    /// Returns the currently buffered unread units.
    ///
    /// # Returns
    ///
    /// Returns a shared slice over the unread portion of the internal unit
    /// buffer. The slice is valid until this adapter is mutated.
    #[must_use]
    #[inline]
    pub fn unread(&self) -> &[I::Item] {
        self.input.unread()
    }

    /// Returns the internal unit buffer capacity.
    ///
    /// # Returns
    ///
    /// The maximum number of units retained in the internal buffer.
    #[must_use]
    #[inline]
    pub fn capacity(&self) -> usize {
        self.input.capacity()
    }

    /// Refills the internal buffer until at least `count` unread units are
    /// available.
    ///
    /// # Parameters
    ///
    /// * `count` - Minimum number of unread units required.
    ///
    /// # Returns
    ///
    /// Returns `true` when at least `count` units are buffered; `false` if EOF
    /// prevents reaching that count. Buffered units remain available in either
    /// case.
    ///
    /// # Errors
    ///
    /// Returns allocation errors mapped to [`ErrorKind::OutOfMemory`], or I/O
    /// errors from the wrapped input while refilling.
    pub fn fill_until(&mut self, count: usize) -> Result<bool> {
        if count > self.input.capacity() {
            self.input.try_reserve_capacity(count).map_err(allocation_error)?;
        }
        self.input.fill_until(count)
    }

    /// Performs one decode step and preserves the transcoder stop status.
    ///
    /// `None` means that the wrapped input reached EOF with no buffered units.
    /// Consumed input is committed before this method returns. Callers can use
    /// the returned [`TranscodeProgress`] to distinguish `NeedOutput` from an
    /// incomplete input tail without guessing from the unread buffer alone.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Streaming decoder accepting the source unit type.
    /// - `M`: Mapper from decoder errors to I/O errors.
    /// - `Value`: Decoded destination value type.
    ///
    /// # Parameters
    ///
    /// - `decoder`: Decoder for the current logical stream.
    /// - `map_error`: Mapper invoked for decoder errors.
    /// - `output`: Destination value storage.
    /// - `output_index`: Start of the writable range.
    /// - `count`: Maximum number of destination values available.
    ///
    /// # Returns
    ///
    /// Returns `Some` validated progress after a decode step, or `None` at EOF
    /// with no buffered units. A zero count returns `Some` zero progress.
    ///
    /// # Errors
    ///
    /// Returns invalid output-range or progress errors, input/refill errors,
    /// or decoder errors translated by `map_error`.
    pub fn transcode_step<D, M, Value>(
        &mut self,
        decoder: &mut D,
        map_error: &mut M,
        output: &mut [Value],
        output_index: usize,
        count: usize,
    ) -> Result<Option<TranscodeProgress>>
    where
        D: Transcoder<Input = I::Item, Output = Value>,
        M: FnMut(D::Error) -> Error,
    {
        let output_end = SliceRange::checked_range_end(
            output.len(),
            output_index,
            count,
            "decoded output range exceeds destination buffer",
        )?;
        if count == 0 {
            return Ok(Some(TranscodeProgress::complete(0, 0)));
        }
        if self.unread_len() == 0 && !self.fill_more()? {
            return Ok(None);
        }
        let available_input = self.unread_len();
        let progress = decoder
            .transcode(self.unread(), 0, &mut output[..output_end], output_index)
            .map_err(&mut *map_error)
            .and_then(|progress| validate_decode_progress(progress, 0, available_input, output_index, count))?;
        self.consume(progress.read());
        Ok(Some(progress))
    }

    /// Performs one decode step after the caller has established EOF.
    ///
    /// This method does not read from the wrapped input. It passes the current
    /// unread buffer to [`Transcoder::transcode_eof`], validates the returned
    /// progress, and commits consumed source units before returning.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Streaming decoder accepting the source unit type.
    /// - `M`: Mapper from decoder errors to I/O errors.
    /// - `Value`: Decoded destination value type.
    ///
    /// # Parameters
    ///
    /// - `decoder`: Decoder for the current logical stream.
    /// - `map_error`: Mapper invoked for decoder errors.
    /// - `output`: Destination value storage.
    /// - `output_index`: Start of the writable range.
    /// - `count`: Maximum number of destination values available.
    ///
    /// # Returns
    ///
    /// Returns validated EOF progress. A zero output count returns zero
    /// progress without calling the decoder; an empty input is still passed to
    /// `transcode_eof` so decoders can handle EOF with retained state.
    ///
    /// # Errors
    ///
    /// Returns invalid output-range errors, or decoder errors mapped by
    /// `map_error`.
    pub fn transcode_eof_step<D, M, Value>(
        &mut self,
        decoder: &mut D,
        map_error: &mut M,
        output: &mut [Value],
        output_index: usize,
        count: usize,
    ) -> Result<TranscodeProgress>
    where
        D: Transcoder<Input = I::Item, Output = Value>,
        M: FnMut(D::Error) -> Error,
    {
        let output_end = SliceRange::checked_range_end(
            output.len(),
            output_index,
            count,
            "decoded EOF output range exceeds destination buffer",
        )?;
        if count == 0 {
            return Ok(TranscodeProgress::complete(0, 0));
        }
        let available_input = self.unread_len();
        let progress = decoder
            .transcode_eof(self.unread(), 0, &mut output[..output_end], output_index)
            .map_err(&mut *map_error)
            .and_then(|progress| validate_decode_progress(progress, 0, available_input, output_index, count))?;
        self.consume(progress.read());
        Ok(progress)
    }

    /// Consumes unread units from the current buffer window.
    ///
    /// # Parameters
    ///
    /// * `count` - Number of unread units to discard.
    ///
    /// # Panics
    ///
    /// Panics when `count` exceeds [`Self::unread_len`].
    #[inline]
    pub fn consume(&mut self, count: usize) {
        assert!(count <= self.unread_len(), "cannot consume beyond buffered input",);
        // SAFETY: The caller-provided count is within the unread window.
        unsafe {
            self.input.consume(count);
        }
    }

    /// Copies unread units into an indexed output range without consuming them.
    ///
    /// # Parameters
    ///
    /// * `output` - Destination storage that receives a copy of unread units.
    /// * `output_index` - Start index inside `output`.
    /// * `count` - Number of unread units to copy.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `output_index..output_index + count` is
    /// a valid range inside `output`, that the addition does not overflow, that
    /// `count <= self.unread_len()`, and that the destination range does not
    /// overlap with the unread units stored inside this buffer.
    pub unsafe fn copy_unread_to(&self, output: &mut [I::Item], output_index: usize, count: usize) {
        // SAFETY: The caller guarantees the destination range and non-overlap
        // requirements for the unread copy.
        let unread = self.unread();
        unsafe {
            UncheckedSlice::copy_nonoverlapping(unread, 0, output, output_index, count);
        }
    }

    /// Consumes this adapter and returns its parts.
    ///
    /// # Returns
    ///
    /// The wrapped input and the buffer holding unread units.
    #[must_use = "the returned input and unread buffer must be handled"]
    #[inline]
    pub fn into_parts(self) -> (I, Buffer<I::Item>) {
        self.input.into_parts()
    }

    /// Reads buffered units into an indexed output range.
    ///
    /// # Parameters
    ///
    /// * `output` - Destination unit storage.
    /// * `output_index` - Start index inside `output`.
    /// * `count` - Maximum number of units to read.
    ///
    /// # Returns
    ///
    /// The number of units copied into `output`.
    ///
    /// # Errors
    ///
    /// Returns input or buffer validation errors from the wrapped
    /// [`qubit_io::BufferedInput`].
    ///
    /// # Panics
    ///
    /// Debug builds panic if the destination range violates the safety
    /// contract.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `output_index..output_index + count` is
    /// a valid range inside `output` and that the addition does not overflow.
    pub unsafe fn read_unchecked(
        &mut self,
        output: &mut [I::Item],
        output_index: usize,
        count: usize,
    ) -> Result<usize> {
        debug_assert!(
            SliceRange::range_fits(output.len(), output_index, count),
            "unchecked read output range exceeds destination buffer",
        );
        if count == 0 {
            return Ok(0);
        }
        // SAFETY: The caller guarantees the destination range is valid.
        unsafe { self.input.read_unchecked(output, output_index, count) }
    }

    /// Decodes one codec value from the buffered unit input.
    ///
    /// This strict convenience method supports codecs whose decode reset and
    /// finish phases do not emit values. Use
    /// [`Self::read_decoded_lifecycle_with`] when those phases have output.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Codec accepting the wrapped input's unit type.
    /// - `M`: Mapper from codec decode errors to I/O errors.
    ///
    /// # Parameters
    ///
    /// * `codec` - Codec used for this single-value decode.
    /// * `map_error` - Mapper for codec-domain invalid-input errors.
    ///
    /// # Returns
    ///
    /// Returns one decoded codec value.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::Unsupported`] before invoking the codec or reading
    /// input when reset or finish may emit values. Otherwise, returns I/O
    /// errors from the wrapped input, `UnexpectedEof` when EOF occurs before a
    /// complete value is available, `InvalidData` when the codec reports an
    /// impossible incomplete state, or the error returned by `map_error` for
    /// codec reset, invalid input, or codec finish failures.
    ///
    /// # Panics
    ///
    /// Panics when the codec reports more reset or finish values than its
    /// declared bounds.
    pub fn read_decoded_with<C, M>(&mut self, codec: &mut C, map_error: M) -> Result<C::Value>
    where
        C: Codec<Unit = I::Item>,
        M: FnMut(C::DecodeError) -> Error,
    {
        TranscodeFailure::ensure_no_decode_lifecycle_output::<C>()
            .map_err(|error| Error::new(ErrorKind::Unsupported, error))?;
        let progress = self.read_decoded_lifecycle_with_scratch_impl(codec, &mut [], &mut [], map_error)?;
        let (value, reset_written, finish_written) = progress.into_parts();
        debug_assert_eq!(0, reset_written);
        debug_assert_eq!(0, finish_written);
        Ok(value)
    }

    /// Decodes one complete codec lifecycle and preserves every output phase.
    ///
    /// The method allocates independent storage for values emitted by
    /// `decode_reset` and `decode_finish`, so neither phase can overwrite the
    /// other.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Codec accepting the wrapped input's unit type.
    /// - `M`: Mapper from codec decode errors to I/O errors.
    ///
    /// # Parameters
    ///
    /// - `codec`: Codec used to decode one complete lifecycle.
    /// - `map_error`: Maps codec decode errors to I/O errors.
    ///
    /// # Returns
    ///
    /// Returns reset output, the main decoded value, and finish output.
    ///
    /// # Errors
    ///
    /// Returns I/O errors from the wrapped input, `UnexpectedEof` when EOF
    /// occurs before a complete value is available, `InvalidData` when the
    /// codec reports an impossible incomplete state, or the error returned
    /// by `map_error` for codec reset, invalid input, or codec finish failures.
    ///
    /// # Panics
    ///
    /// Panics when the codec reports more reset or finish values than its
    /// declared bounds.
    pub fn read_decoded_lifecycle_with<C, M>(
        &mut self,
        codec: &mut C,
        map_error: M,
    ) -> Result<DecodeLifecycleOutput<C::Value>>
    where
        C: Codec<Unit = I::Item>,
        C::Value: Default,
        M: FnMut(C::DecodeError) -> Error,
    {
        assert_unit_bounds::<C>();
        let mut reset_output = Vec::new();
        reset_output.resize_with(C::MAX_DECODE_RESET_VALUES, C::Value::default);
        let mut finish_output = Vec::new();
        finish_output.resize_with(C::MAX_DECODE_FINISH_VALUES, C::Value::default);
        let progress =
            self.read_decoded_lifecycle_with_scratch_impl(codec, &mut reset_output, &mut finish_output, map_error)?;
        let (value, reset_written, finish_written) = progress.into_parts();
        reset_output.truncate(reset_written);
        finish_output.truncate(finish_written);
        Ok(DecodeLifecycleOutput::new(reset_output, value, finish_output))
    }

    /// Decodes one complete codec lifecycle into separate caller storage.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Codec accepting the wrapped input's unit type.
    /// - `M`: Mapper from codec decode errors to I/O errors.
    ///
    /// # Parameters
    ///
    /// - `codec`: Codec used to decode one complete lifecycle.
    /// - `reset_output`: Reusable storage for values emitted by
    ///   [`Codec::decode_reset`].
    /// - `finish_output`: Reusable storage for values emitted by
    ///   [`Codec::decode_finish`].
    /// - `map_error`: Maps codec decode errors to I/O errors.
    ///
    /// # Returns
    ///
    /// Returns the main decoded value and the initialized lengths of both
    /// lifecycle output buffers.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] when either output buffer is shorter
    /// than the corresponding codec bound. Returns I/O errors from the wrapped
    /// input, `UnexpectedEof` when EOF occurs before a complete value is
    /// available, `InvalidData` when the codec reports an impossible
    /// incomplete state, or the error returned by `map_error` for codec reset,
    /// invalid input, or codec finish failures.
    ///
    /// # Panics
    ///
    /// Panics when the codec reports more reset or finish values than its
    /// declared bounds.
    pub fn read_decoded_lifecycle_with_scratch<C, M>(
        &mut self,
        codec: &mut C,
        reset_output: &mut [C::Value],
        finish_output: &mut [C::Value],
        map_error: M,
    ) -> Result<DecodeLifecycleProgress<C::Value>>
    where
        C: Codec<Unit = I::Item>,
        M: FnMut(C::DecodeError) -> Error,
    {
        self.read_decoded_lifecycle_with_scratch_impl(codec, reset_output, finish_output, map_error)
    }

    /// Runs decoder reset into an indexed output range.
    ///
    /// This method does not read or consume buffered input units.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Streaming decoder accepting the source unit type.
    /// - `M`: Mapper from decoder errors to I/O errors.
    /// - `Value`: Decoded destination value type.
    ///
    /// # Parameters
    ///
    /// - `decoder`: Decoder for the current logical stream.
    /// - `map_error`: Mapper invoked for decoder errors.
    /// - `output`: Destination value storage.
    /// - `output_index`: Start of the writable range.
    /// - `count`: Maximum number of destination values available.
    ///
    /// # Returns
    ///
    /// Returns the number of reset values initialized in the requested range.
    ///
    /// # Errors
    ///
    /// Returns invalid output ranges, insufficient declared output capacity,
    /// capacity errors, or reset errors mapped by `map_error`.
    ///
    /// # Panics
    ///
    /// Panics when the decoder reports writing more values than its declared
    /// reset bound.
    pub fn reset<D, M, Value>(
        &self,
        decoder: &mut D,
        map_error: &mut M,
        output: &mut [Value],
        output_index: usize,
        count: usize,
    ) -> Result<usize>
    where
        D: Transcoder<Input = I::Item, Output = Value>,
        M: FnMut(D::Error) -> Error,
    {
        let required = decoder.max_reset_output_len().map_err(capacity_to_io_error)?;
        let output_end = SliceRange::checked_range_end(
            output.len(),
            output_index,
            count,
            "reset output range exceeds destination buffer",
        )?;
        if count < required {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "insufficient output for decoder reset bound",
            ));
        }
        let output = &mut output[..output_end];
        let written = decoder.reset(output, output_index).map_err(&mut *map_error)?;
        assert!(written <= required, "reset wrote beyond its bound");
        Ok(written)
    }

    /// Decodes values into an indexed output range using a streaming
    /// [`Transcoder`].
    ///
    /// # Type Parameters
    ///
    /// - `D`: Streaming decoder accepting the source unit type.
    /// - `M`: Mapper from decoder errors to I/O errors.
    /// - `Value`: Decoded destination value type.
    ///
    /// # Parameters
    ///
    /// * `decoder` - Streaming decoder used for this operation.
    /// * `map_error` - Function mapping transcode errors into I/O errors.
    /// * `output` - Destination value storage.
    /// * `output_index` - Start index inside `output`.
    /// * `count` - Maximum number of values to write.
    ///
    /// # Returns
    ///
    /// The number of values written. When this method is driven through EOF
    /// with output capacity remaining, it passes the retained tail—or an empty
    /// input when no tail remains—to [`Transcoder::transcode_eof`] before
    /// returning.
    ///
    /// # Errors
    ///
    /// Returns input errors, invalid output ranges, capacity errors from the
    /// internal buffer, or transcode errors mapped by `map_error`.
    /// This operation is not transactional. An error may be returned after
    /// source units have been consumed and values have been written to
    /// output. Progress is not rolled back, and the error does not report
    /// the accumulated output length. Use `transcode_step` and commit each
    /// successful progress result when previously decoded values must
    /// remain observable after a later failure.
    pub fn transcode<D, M, Value>(
        &mut self,
        decoder: &mut D,
        map_error: &mut M,
        output: &mut [Value],
        output_index: usize,
        count: usize,
    ) -> Result<usize>
    where
        D: Transcoder<Input = I::Item, Output = Value>,
        M: FnMut(D::Error) -> Error,
    {
        let output_end = SliceRange::checked_range_end(
            output.len(),
            output_index,
            count,
            "decoded output range exceeds destination buffer",
        )?;
        if count == 0 {
            return Ok(0);
        }
        let output = &mut output[..output_end];
        let mut written_total = 0;
        loop {
            if self.unread_len() == 0 && !self.fill_more()? {
                let remaining_output = count - written_total;
                let eof_progress = self.transcode_eof_step(
                    decoder,
                    map_error,
                    output,
                    output_index + written_total,
                    remaining_output,
                )?;
                written_total += eof_progress.written();
                return Ok(written_total);
            }
            let units = self.unread();
            let available_input = units.len();
            let remaining_output = count - written_total;
            let progress = decoder
                .transcode(units, 0, output, output_index + written_total)
                .map_err(&mut *map_error)?;
            let progress = validate_decode_progress(
                progress,
                0,
                available_input,
                output_index + written_total,
                remaining_output,
            )?;
            let consumed = progress.read();
            let written = progress.written();
            self.consume(consumed);
            written_total += written;
            match progress.status() {
                TranscodeStatus::Complete => {
                    if written_total == count {
                        return Ok(written_total);
                    }
                }
                TranscodeStatus::NeedOutput { .. } => {
                    return Ok(written_total);
                }
                TranscodeStatus::NeedInput { required, .. } => {
                    if self.fill_until(required.get())? {
                        continue;
                    }
                    let remaining_output = count - written_total;
                    let eof_progress = self.transcode_eof_step(
                        decoder,
                        map_error,
                        output,
                        output_index + written_total,
                        remaining_output,
                    )?;
                    written_total += eof_progress.written();
                    return Ok(written_total);
                }
            }
        }
    }

    /// Finishes a streaming decoder into an indexed output range.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Streaming decoder accepting the source unit type.
    /// - `M`: Mapper from decoder errors to I/O errors.
    /// - `Value`: Decoded destination value type.
    ///
    /// # Parameters
    ///
    /// * `decoder` - Streaming decoder whose final output is being collected.
    /// * `map_error` - Function mapping transcode errors into I/O errors.
    /// * `output` - Destination value storage.
    /// * `output_index` - Start index inside `output`.
    /// * `count` - Maximum number of finish values to write.
    ///
    /// # Returns
    ///
    /// The number of values written by the decoder finish operation.
    ///
    /// # Errors
    ///
    /// Returns invalid output ranges, capacity errors, or transcode
    /// finalization errors mapped to I/O errors.
    ///
    /// # Panics
    ///
    /// Panics when the decoder reports writing more values than its
    /// [`Transcoder::max_finish_output_len`] bound.
    pub fn finish<D, M, Value>(
        &self,
        decoder: &mut D,
        map_error: &mut M,
        output: &mut [Value],
        output_index: usize,
        count: usize,
    ) -> Result<usize>
    where
        D: Transcoder<Input = I::Item, Output = Value>,
        M: FnMut(D::Error) -> Error,
    {
        let required = decoder.max_finish_output_len().map_err(capacity_to_io_error)?;
        // Validate the caller-supplied count range first (InvalidInput).
        let output_end = SliceRange::checked_range_end(
            output.len(),
            output_index,
            count,
            "finish output range exceeds destination buffer",
        )?;
        // `count` is the caller's declared writable finish range.  The
        // destination slice may be larger, but passing extra capacity to the
        // decoder would allow it to write beyond the range the caller granted.
        if count < required {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "insufficient output for decoder finish bound",
            ));
        }
        let output = &mut output[..output_end];
        let written = decoder.finish(output, output_index).map_err(&mut *map_error)?;
        assert!(written <= required, "finish wrote beyond its bound");
        Ok(written)
    }
}

impl<I> TranscodeDecodeInput<I>
where
    I: SeekableByteInput,
{
    /// Seeks the wrapped byte input and discards buffered bytes after success.
    ///
    /// # Parameters
    ///
    /// * `position` - Target seek position.
    ///
    /// # Returns
    ///
    /// The new stream position reported by the wrapped input.
    ///
    /// # Errors
    ///
    /// Returns seek errors from the wrapped input.
    #[inline]
    pub fn seek(&mut self, position: SeekFrom) -> Result<u64> {
        self.input.seek_to(position)
    }
}

impl<I> TranscodeDecodeInput<I>
where
    I: Input,
    I::Item: Copy + Default,
{
    /// Reads and decodes reset, body, and finish output using caller scratch
    /// buffers.
    ///
    /// This internal path keeps lifecycle allocation and error mapping in one
    /// place for the public convenience methods.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Codec accepting the wrapped input's unit type.
    /// - `M`: Mapper from codec decode errors to I/O errors.
    ///
    /// # Parameters
    ///
    /// - `codec`: Codec whose reset, decode, and finish phases are executed.
    /// - `reset_output`: Separate storage for reset values.
    /// - `finish_output`: Separate storage for finish values.
    /// - `map_error`: Mapper for codec decode errors.
    ///
    /// # Returns
    ///
    /// Returns the decoded value and initialized lengths of both output
    /// buffers.
    ///
    /// # Errors
    ///
    /// Returns InvalidInput for insufficient scratch capacity, input I/O
    /// errors, UnexpectedEof for a truncated value, InvalidData for invalid
    /// codec progress, or mapped codec reset, decode, and finish errors.
    ///
    /// # Panics
    ///
    /// Panics if reset or finish reports output beyond its declared bound.
    fn read_decoded_lifecycle_with_scratch_impl<C, M>(
        &mut self,
        codec: &mut C,
        reset_output: &mut [C::Value],
        finish_output: &mut [C::Value],
        mut map_error: M,
    ) -> Result<DecodeLifecycleProgress<C::Value>>
    where
        C: Codec<Unit = I::Item>,
        M: FnMut(C::DecodeError) -> Error,
    {
        assert_unit_bounds::<C>();
        if reset_output.len() < C::MAX_DECODE_RESET_VALUES {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "decode reset output is shorter than the codec reset bound",
            ));
        }
        if finish_output.len() < C::MAX_DECODE_FINISH_VALUES {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "decode finish output is shorter than the codec finish bound",
            ));
        }
        let reset_written = unsafe {
            // SAFETY: The reset output length check above reserves the codec's
            // declared decode-reset output bound.
            codec.decode_reset(reset_output, 0)
        }
        .map_err(&mut map_error)?;
        assert!(
            reset_written <= C::MAX_DECODE_RESET_VALUES,
            "Codec::decode_reset wrote beyond its reset bound",
        );

        let value = CodecDecodeDriver::new(&mut self.input).read_one(codec, &mut map_error)?;

        let finish_written = unsafe {
            // SAFETY: The finish output length check above reserves the
            // codec's declared decode-finish output bound.
            codec.decode_finish(finish_output, 0)
        }
        .map_err(&mut map_error)?;
        assert!(
            finish_written <= C::MAX_DECODE_FINISH_VALUES,
            "Codec::decode_finish wrote beyond its finish bound",
        );
        Ok(DecodeLifecycleProgress::new(value, reset_written, finish_written))
    }

    /// Refills the underlying buffer.
    ///
    /// # Returns
    ///
    /// Returns `true` if unread input is available after refill, or `false` at
    /// EOF.
    ///
    /// # Errors
    ///
    /// Propagates errors from the wrapped input while refilling.
    #[inline]
    fn fill_more(&mut self) -> Result<bool> {
        self.input.fill_more()
    }
}

impl<I> Read for TranscodeDecodeInput<I>
where
    I: ByteInput,
{
    /// Reads raw bytes through the internal buffer.
    ///
    /// # Parameters
    ///
    /// - `output`: Destination for raw buffered bytes.
    ///
    /// # Returns
    ///
    /// Returns the number of bytes read; zero indicates EOF or an empty
    /// destination.
    ///
    /// # Errors
    ///
    /// Propagates wrapped input or buffer errors.
    fn read(&mut self, output: &mut [u8]) -> Result<usize> {
        // SAFETY: The full output slice is a valid destination range.
        unsafe { self.read_unchecked(output, 0, output.len()) }
    }
}

impl<I> Seek for TranscodeDecodeInput<I>
where
    I: SeekableByteInput,
{
    /// Seeks the wrapped byte input and discards buffered bytes after success.
    ///
    /// # Parameters
    ///
    /// - `position`: Target byte-stream position.
    ///
    /// # Returns
    ///
    /// Returns the new byte offset after clearing buffered data.
    ///
    /// # Errors
    ///
    /// Propagates wrapped seek errors, preserving the buffer when seeking
    /// fails.
    fn seek(&mut self, position: SeekFrom) -> Result<u64> {
        self.seek(position)
    }
}

impl<I> Debug for TranscodeDecodeInput<I>
where
    I: Input,
    I::Item: Copy + Default,
    BufferedInput<I>: Debug,
{
    /// Formats this buffered decode input for debugging.
    ///
    /// # Parameters
    ///
    /// - `formatter`: Formatting sink receiving the struct and owned input.
    ///
    /// # Returns
    ///
    /// Returns success after writing the debug representation.
    ///
    /// # Errors
    ///
    /// Propagates a formatting error from the sink or wrapped input.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FormatResult {
        formatter
            .debug_struct("TranscodeDecodeInput")
            .field("input", &self.input)
            .finish()
    }
}

/// Converts a capacity planning failure into an I/O error.
///
/// # Parameters
///
/// - `error`: Capacity failure preserved as the I/O error source.
///
/// # Returns
///
/// Returns an `InvalidData` I/O error owning the capacity failure.
fn capacity_to_io_error(error: CapacityError) -> Error {
    Error::new(ErrorKind::InvalidData, error)
}