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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Reusable buffered encoder engine.

use core::num::NonZeroUsize;

use super::super::internal::encode_attempt::EncodeAttempt;
use super::super::internal::encode_state::EncodeState;
use super::super::internal::lifecycle_guard::LifecycleGuard;
use super::EncodeOutcome;
use super::EncodeUnencodableAction;
use super::TranscodeEncodeHooks;
use crate::CapacityError;
use crate::Codec;
use crate::TranscodeEncodeError;
use crate::TranscodeEncodeErrorOf;
use crate::TranscodeEncoder;
use crate::TranscodeFailure;
use crate::TranscodeProgress;
use crate::Transcoder;
use crate::codec::assert_unit_bounds;

/// Reusable buffered encoding engine for codec-backed encoders.
///
/// The engine owns the low-level codec and hook object. It keeps the common
/// buffered encoding loop private: input-index validation, output-capacity
/// checks, input consumption, output progress, and [`crate::TranscodeStatus`]
/// reporting.
///
/// Use this type to build a streaming encoder over a one-value [`Codec`]. The
/// engine does not allocate output. It encodes values accepted by
/// [`Codec::can_encode_value`] directly through the codec. When a value is
/// outside the codec's encodable domain, the engine asks hooks whether to
/// reject, skip, or replace it. If the current output buffer is too small for
/// the selected value, the engine returns
/// [`crate::TranscodeStatus::NeedOutput`] without consuming that input; the
/// caller can provide a larger or fresh output buffer and resume with the
/// returned input index.
///
/// For the common strict policy that simply wraps codec errors, use
/// [`crate::CodecTranscodeEncoder`]. Use `TranscodeEncodeEngine` directly when
/// the encode policy needs custom planning, replacement, skipped values, or
/// finish-time output.
///
/// # Examples
///
/// ```rust
/// use core::convert::Infallible;
/// use core::num::NonZeroUsize;
///
/// use qubit_codec::Codec;
/// use qubit_codec::DecodeFailure;
/// use qubit_codec::TranscodeEncodeErrorOf;
/// use qubit_codec::TranscodeStatus;
/// use qubit_codec::engine::EncodeContext;
/// use qubit_codec::engine::EncodeUnencodableAction;
/// use qubit_codec::engine::TranscodeEncodeEngine;
/// use qubit_codec::engine::TranscodeEncodeHooks;
///
/// #[derive(Clone, Copy)]
/// 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<Self::DecodeError>> {
///         Ok((input[index], NonZeroUsize::MIN))
///     }
///
///     unsafe fn encode(
///         &mut self,
///         value: &u8,
///         output: &mut [u8],
///         index: usize,
///     ) -> Result<usize, Self::EncodeError> {
///         output[index] = *value;
///         Ok(1)
///     }
/// }
///
/// struct StrictHooks;
///
/// impl TranscodeEncodeHooks<ByteCodec> for StrictHooks {
///     fn handle_unencodable_encode(
///         &mut self,
///         _codec: &mut ByteCodec,
///         _context: &EncodeContext<'_, u8>,
///     ) -> Result<EncodeUnencodableAction<u8>, TranscodeEncodeErrorOf<ByteCodec>> {
///         unreachable!("ByteCodec accepts every u8")
///     }
/// }
///
/// let mut engine = TranscodeEncodeEngine::new(ByteCodec, StrictHooks);
/// let input = [1_u8, 2, 3];
/// let mut output = [0_u8; 2];
/// let mut reset_output = [];
/// engine.reset(&mut reset_output, 0)?;
///
/// let progress = engine.transcode(&input, 0, &mut output, 0)?;
/// match progress.status() {
///     TranscodeStatus::Complete => unreachable!("output is intentionally short"),
///     TranscodeStatus::NeedOutput { .. } => {
///         assert_eq!(2, progress.written());
///         assert_eq!([1, 2], output);
///         // Write out `output[..progress.written()]`, then resume at
///         // `progress.read()` with fresh output capacity.
///     }
///     TranscodeStatus::NeedInput { .. } => unreachable!("encoders do not read encoded input"),
/// }
/// # Ok::<(), TranscodeEncodeErrorOf<ByteCodec>>(())
/// ```
///
/// # Type Parameters
///
/// - `C`: Low-level codec used by the engine.
/// - `H`: Policy hook object used by the engine.
#[derive(Debug)]
pub struct TranscodeEncodeEngine<C, H> {
    /// Owned codec carrying the encode-side stream state.
    codec: C,
    /// Owned policy hooks for unsupported values and lifecycle output.
    hooks: H,
    /// Guard for the `reset → transcode* → finish` lifecycle in every build
    /// profile.
    lifecycle: LifecycleGuard,
}

impl<C, H> TranscodeEncodeEngine<C, H>
where
    C: Codec,
    H: TranscodeEncodeHooks<C>,
{
    /// Creates a buffered encoder engine.
    ///
    /// # Parameters
    ///
    /// - `codec`: Low-level codec used for one-value encoding.
    /// - `hooks`: Policy hooks used for planning and writing values.
    ///
    /// # Returns
    ///
    /// Returns a buffered encoder engine.
    ///
    /// # Compile-Time Checks
    ///
    /// Fails to compile when the supplied codec declares a zero decode unit
    /// bound or when [`Codec::MIN_UNITS_PER_VALUE`] exceeds
    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`]. The encode bound may be zero for
    /// a fully buffered codec.
    #[inline]
    #[must_use]
    pub fn new(codec: C, hooks: H) -> Self {
        assert_unit_bounds::<C>();
        Self {
            codec,
            hooks,
            lifecycle: LifecycleGuard::new(),
        }
    }

    /// Returns the wrapped low-level codec.
    ///
    /// # Returns
    ///
    /// Returns a shared reference to the codec owned by this engine.
    #[inline]
    #[must_use = "use the codec reference to inspect the wrapped codec"]
    pub const fn codec(&self) -> &C {
        &self.codec
    }

    /// Returns the wrapped low-level codec mutably.
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to the codec owned by this engine.
    #[inline]
    #[must_use = "use the codec reference to configure the wrapped codec"]
    pub fn codec_mut(&mut self) -> &mut C {
        &mut self.codec
    }

    /// Returns the encode hooks used by this engine.
    ///
    /// # Returns
    ///
    /// Returns a shared reference to the hook object owned by this engine.
    #[inline]
    #[must_use = "use the hook reference to inspect the encode policy"]
    pub const fn hooks(&self) -> &H {
        &self.hooks
    }

    /// Returns the encode hooks mutably.
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to the hook object owned by this engine.
    #[inline]
    #[must_use = "use the hook reference to configure the encode policy"]
    pub fn hooks_mut(&mut self) -> &mut H {
        &mut self.hooks
    }

    /// Consumes the engine and returns its codec and hooks.
    ///
    /// Any lifecycle state owned by the engine is discarded.
    ///
    /// # Returns
    ///
    /// Returns the wrapped codec followed by the encode hooks.
    #[inline]
    #[must_use]
    pub fn into_parts(self) -> (C, H) {
        let Self { codec, hooks, .. } = self;
        (codec, hooks)
    }

    /// Gets a conservative upper bound for output units needed for
    /// `input_len` values.
    ///
    /// This bound covers only the streaming encode phase. It is delegated to
    /// [`TranscodeEncodeHooks::max_transcode_output_len`], so it includes hook
    /// policy and is valid for every reachable transient codec and hook state.
    /// Downstream encoders must use this engine-level API for capacity planning
    /// instead of recomputing the bound from [`Codec`] constants.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Number of input values the caller plans to encode.
    ///
    /// # Returns
    ///
    /// Returns a conservative upper bound for output units.
    ///
    /// # Errors
    ///
    /// Returns a capacity error when hook planning overflows.
    #[inline]
    pub fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        self.hooks.max_transcode_output_len(&self.codec, input_len)
    }

    /// Gets the global maximum output units emitted by stream reset.
    ///
    /// # Returns
    ///
    /// Returns the codec's reset-output upper bound. This query never fails.
    #[inline]
    pub fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
        Ok(C::MAX_ENCODE_RESET_UNITS)
    }

    /// Gets the global maximum output units emitted by finishing codec and hook
    /// state.
    ///
    /// Returns the sum of [`Codec::MAX_ENCODE_FINISH_UNITS`] and the
    /// hook-provided final-output bound. The codec finish portion covers units
    /// written by [`Codec::encode_finish`]; hook implementations must not
    /// include that portion in
    /// [`TranscodeEncodeHooks::max_finish_output_len`]. Both component bounds
    /// cover every reachable transient state.
    ///
    /// # Returns
    ///
    /// Returns the combined codec-finish and hook-finish output bound.
    ///
    /// # Errors
    ///
    /// Returns [`CapacityError::OutputLengthOverflow`] when the sum overflows.
    #[inline]
    pub fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
        C::MAX_ENCODE_FINISH_UNITS
            .checked_add(self.hooks.max_finish_output_len(&self.codec))
            .ok_or(CapacityError::OutputLengthOverflow)
    }

    /// Gets the maximum output units needed by a complete one-shot encode
    /// stream.
    ///
    /// The returned bound covers reset output, the streaming encode phase for
    /// `input_len` values, and finish output. Its components are global across
    /// transient state. Higher-level complete encode helpers should use this
    /// engine-level bound instead of recomputing capacity from [`Codec`]
    /// constants, because hook policy may change streaming or finish output.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Number of input values in the complete stream.
    ///
    /// # Returns
    ///
    /// Returns the complete-stream output bound.
    ///
    /// # Errors
    ///
    /// Returns a capacity error if a component query or their sum overflows.
    #[inline]
    pub fn max_total_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        let reset = self.max_reset_output_len()?;
        let transcode = self.max_transcode_output_len(input_len)?;
        let finish = self.max_finish_output_len()?;
        reset
            .checked_add(transcode)
            .and_then(|len| len.checked_add(finish))
            .ok_or(CapacityError::OutputLengthOverflow)
    }

    /// Resets codec encode state, hook-owned state, and stream-start output.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of reset units written.
    ///
    /// # Errors
    ///
    /// Returns framework errors when the caller provides invalid or
    /// insufficient output capacity. Returns domain errors when codec reset or
    /// hook reset handling fails. Capacity and index failures occur before any
    /// reset state is changed. Once reset execution starts, an error poisons
    /// the engine until a later reset succeeds.
    ///
    /// # Panics
    ///
    /// Panics if the codec reports reset output beyond its declared bound.
    pub fn reset(&mut self, output: &mut [C::Unit], output_index: usize) -> Result<usize, TranscodeEncodeErrorOf<C>> {
        let required = self.max_reset_output_len()?;
        TranscodeFailure::ensure_output_capacity(output.len(), output_index, required)?;
        self.lifecycle.on_reset_start();
        self.hooks.reset_hooks(&mut self.codec);
        let written = unsafe {
            // SAFETY: The capacity check above reserves the codec's declared
            // reset-output bound at `output_index`.
            self.codec.encode_reset(output, output_index)
        }
        .map_err(TranscodeEncodeError::domain_reset)?;
        assert!(written <= required, "Codec::encode_reset wrote beyond its reset bound",);
        self.lifecycle.on_reset_success();
        Ok(written)
    }

    /// Encodes values into a caller-provided output buffer.
    ///
    /// The engine stops before consuming the next input value when the current
    /// output buffer does not satisfy that value's planned capacity bound.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete input value slice visible to the encoder.
    /// - `input_index`: Absolute input value index where encoding starts.
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns progress describing input values consumed, output units written,
    /// and why encoding stopped.
    ///
    /// # Errors
    ///
    /// Returns framework errors when `input_index` is outside `input` or
    /// `output_index` is outside `output`, and domain errors when codec or
    /// hook processing fails or rejects a value. Returns
    /// [`TranscodeFailure::TranscodeBeforeReset`] when the engine has not
    /// completed its first reset. Returns
    /// [`TranscodeFailure::TranscodeAfterFinish`] when the logical stream was
    /// already finished and has not been reset, or
    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
    /// failed after execution started.
    ///
    /// # Panics
    ///
    /// Panics if the codec violates its declared encode length or hooks
    /// return an unencodable replacement.
    pub fn transcode(
        &mut self,
        input: &[C::Value],
        input_index: usize,
        output: &mut [C::Unit],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeEncodeErrorOf<C>> {
        self.lifecycle.on_transcode()?;
        TranscodeFailure::ensure_transcode_indices(input.len(), input_index, output.len(), output_index)?;
        let mut state = EncodeState::new(input, input_index, output, output_index);

        while state.has_input() {
            // SAFETY: The loop condition proves that the current input cursor
            // points at an available value.
            let attempt = unsafe { state.context_unchecked() };
            let outcome = self.encode_one(attempt)?;
            if let Some(progress) = state.apply_encode_outcome(outcome) {
                return Ok(progress);
            }
        }

        Ok(state.complete_progress())
    }

    /// Finishes codec and hook-owned output after EOF.
    ///
    /// Finalization first finishes encode-side codec state through
    /// [`Codec::encode_finish`], then lets hook implementations finish their
    /// own retained state. The caller must provide enough output capacity for
    /// [`TranscodeEncodeEngine::max_finish_output_len`], which includes both
    /// the codec finish bound and the hook-owned finish bound.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of units written by finalization.
    ///
    /// # Errors
    ///
    /// Returns framework errors when the caller provides invalid or
    /// insufficient output capacity. Returns domain errors when codec finish or
    /// hook finalization fails. Returns
    /// [`TranscodeFailure::FinishBeforeReset`] when the engine has not
    /// completed its first reset. Returns
    /// [`TranscodeFailure::FinishAfterFinish`] when the logical stream was
    /// already finished and has not been reset, or
    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
    /// failed after execution started. Capacity and index failures occur before
    /// finish execution and remain retryable; later failures poison the engine
    /// until reset succeeds.
    ///
    /// # Panics
    ///
    /// Panics when the codec finish or finish hooks write beyond their
    /// independently declared output bounds.
    pub fn finish(&mut self, output: &mut [C::Unit], output_index: usize) -> Result<usize, TranscodeEncodeErrorOf<C>> {
        self.lifecycle.on_finish_attempt()?;
        let hook_required = self.hooks.max_finish_output_len(&self.codec);
        let required = C::MAX_ENCODE_FINISH_UNITS
            .checked_add(hook_required)
            .ok_or(CapacityError::OutputLengthOverflow)?;
        TranscodeFailure::ensure_output_capacity(output.len(), output_index, required)?;
        self.lifecycle.on_finish_start();
        let finished = unsafe {
            // SAFETY: The capacity check above reserves the codec's declared
            // finish-output bound at `output_index`.
            self.codec.encode_finish(output, output_index)
        }
        .map_err(TranscodeEncodeError::domain_finish)?;
        assert!(
            finished <= C::MAX_ENCODE_FINISH_UNITS,
            "Codec::encode_finish wrote beyond its finish bound",
        );
        let written = self
            .hooks
            .finish_hooks(&mut self.codec, output, output_index + finished)?;
        assert!(
            written <= hook_required,
            "TranscodeEncodeEngine hook wrote beyond its finish bound",
        );
        self.lifecycle.on_finish_success();
        Ok(finished + written)
    }

    /// Runs a complete one-shot `reset -> transcode -> finish` encode stream.
    ///
    /// The complete input is supplied as `input`, and output starts at index
    /// `0` in `output`. Callers that need subranges should slice their
    /// buffers before calling this method. Downstream one-shot encoder
    /// helpers should call this engine method instead of reproducing the
    /// reset, transcode, and finish sequence themselves.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete input values.
    /// - `output`: Output unit slice for the whole encoded stream.
    ///
    /// # Returns
    ///
    /// Returns the number of output units written.
    ///
    /// # Errors
    ///
    /// Returns framework errors for insufficient output or capacity overflow,
    /// and domain errors from reset, encode, or finish.
    ///
    /// # Panics
    ///
    /// Panics if codec or hook implementations violate the output or
    /// replacement contracts of [`Self::reset`], [`Self::transcode`], or
    /// [`Self::finish`].
    #[inline]
    pub fn transcode_complete_into(
        &mut self,
        input: &[C::Value],
        output: &mut [C::Unit],
    ) -> Result<usize, TranscodeEncodeErrorOf<C>> {
        <Self as Transcoder>::transcode_complete_into(self, input, output)
    }

    /// Encodes one value through the codec and unencodable-value hooks.
    ///
    /// This is the single entry point for `TranscodeConvertEngine` to drive
    /// the encode side without accessing `codec` and `hooks` directly.
    ///
    /// # Parameters
    ///
    /// - `attempt`: Current value, absolute indices, and writable output
    ///   buffer.
    ///
    /// # Returns
    ///
    /// Returns whether the value was consumed or needs more output capacity.
    ///
    /// For an unencodable value, this checks capacity for the codec's maximum
    /// value width before invoking policy hooks. A shortage returns
    /// `NeedOutput` without changing hook state; this conservative requirement
    /// also applies when the hook would skip or reject. Errors after a hook
    /// runs do not roll back mutations made by that hook.
    ///
    /// # Errors
    ///
    /// Returns an engine-domain error when the codec fails or when the hook
    /// rejects an unencodable value.
    ///
    /// # Panics
    ///
    /// Panics if the codec violates its encode length contract or hooks
    /// supply an unencodable replacement.
    pub(in crate::transcode) fn encode_one(
        &mut self,
        attempt: EncodeAttempt<'_, C::Value, C::Unit>,
    ) -> Result<EncodeOutcome, TranscodeEncodeErrorOf<C>> {
        let encodable = {
            let context = attempt.context();
            self.codec.can_encode_value(context.input_value())
        };
        if encodable {
            return self.encode_encodable_value(attempt);
        }
        let required = C::MAX_ENCODE_UNITS_PER_VALUE;
        if attempt.available_output() < required {
            return Ok(EncodeOutcome::need_output(
                NonZeroUsize::new(required).expect("required output is non-zero when capacity is insufficient"),
            ));
        }
        let action = {
            let context = attempt.context();
            self.hooks.handle_unencodable_encode(&mut self.codec, &context)?
        };
        self.apply_unencodable_action(action, attempt)
    }

    /// Encodes an encodable input value.
    ///
    /// # Parameters
    ///
    /// - `attempt`: Current value, absolute indices, and writable output
    ///   buffer.
    ///
    /// # Returns
    ///
    /// Returns the encode outcome for the current value.
    ///
    /// # Errors
    ///
    /// Returns a codec error when encoding fails.
    ///
    /// # Panics
    ///
    /// Panics when [`Codec::encode_len`] exceeds
    /// [`Codec::MAX_ENCODE_UNITS_PER_VALUE`] or [`Codec::encode`] writes a
    /// different number of units than planned.
    fn encode_encodable_value(
        &mut self,
        attempt: EncodeAttempt<'_, C::Value, C::Unit>,
    ) -> Result<EncodeOutcome, TranscodeEncodeErrorOf<C>> {
        let required = self.codec.encode_len(attempt.value());
        assert!(
            required <= C::MAX_ENCODE_UNITS_PER_VALUE,
            "Codec::encode_len exceeded Codec::MAX_ENCODE_UNITS_PER_VALUE",
        );
        if attempt.available_output() < required {
            return Ok(EncodeOutcome::need_output(
                NonZeroUsize::new(required).expect("required output is non-zero when capacity is insufficient"),
            ));
        }
        let (value, input_index, output, output_index) = attempt.into_parts();
        let written = unsafe {
            // SAFETY: The capacity check above reserves the exact value width.
            self.codec.encode(value, output, output_index)
        }
        .map_err(|error| TranscodeEncodeError::domain_main(error, input_index))?;
        assert!(
            written == required,
            "Codec::encode wrote a different length than Codec::encode_len",
        );
        Ok(EncodeOutcome::consumed(written))
    }

    /// Applies the hook-selected unencodable-value action.
    ///
    /// # Parameters
    ///
    /// - `action`: Policy action selected by the encode hooks.
    /// - `attempt`: Rejected value, absolute indices, and writable output
    ///   buffer.
    ///
    /// # Returns
    ///
    /// Returns the encode outcome for the current input value.
    ///
    /// # Errors
    ///
    /// Returns an unencodable-value error for rejection, or a codec-domain
    /// error when replacement encoding fails.
    ///
    /// # Panics
    ///
    /// Panics if replacement encoding violates the codec length contract or
    /// the replacement cannot be encoded.
    #[inline]
    fn apply_unencodable_action(
        &mut self,
        action: EncodeUnencodableAction<C::Value>,
        attempt: EncodeAttempt<'_, C::Value, C::Unit>,
    ) -> Result<EncodeOutcome, TranscodeEncodeErrorOf<C>> {
        match action {
            EncodeUnencodableAction::Reject => {
                // Keep the streaming encoder usable for non-Clone values.
                // The failure still carries the absolute input index; callers
                // that need value context can add it in a higher-level facade.
                Err(TranscodeEncodeError::unencodable_without_context(attempt.input_index()))
            }
            EncodeUnencodableAction::Skip => Ok(EncodeOutcome::consumed(0)),
            EncodeUnencodableAction::Replace { value } => self.encode_replacement_value(value, attempt),
        }
    }

    /// Encodes a hook-provided replacement value.
    ///
    /// # Parameters
    ///
    /// - `value`: Replacement value selected by hooks.
    /// - `attempt`: Original value, absolute indices, and writable output
    ///   buffer.
    ///
    /// # Returns
    ///
    /// Returns the encode outcome for the replacement.
    ///
    /// # Errors
    ///
    /// Returns a codec error when replacement encoding fails.
    ///
    /// # Panics
    ///
    /// Panics when hooks return a replacement value that the codec cannot
    /// encode, [`Codec::encode_len`] exceeds
    /// [`Codec::MAX_ENCODE_UNITS_PER_VALUE`], or [`Codec::encode`] writes a
    /// different number of units than planned.
    fn encode_replacement_value(
        &mut self,
        value: C::Value,
        attempt: EncodeAttempt<'_, C::Value, C::Unit>,
    ) -> Result<EncodeOutcome, TranscodeEncodeErrorOf<C>> {
        assert!(
            self.codec.can_encode_value(&value),
            "EncodeUnencodableAction::Replace returned an unencodable replacement value",
        );
        let required = self.codec.encode_len(&value);
        assert!(
            required <= C::MAX_ENCODE_UNITS_PER_VALUE,
            "Codec::encode_len exceeded Codec::MAX_ENCODE_UNITS_PER_VALUE",
        );
        if attempt.available_output() < required {
            return Ok(EncodeOutcome::need_output(
                NonZeroUsize::new(required).expect("required output is non-zero when capacity is insufficient"),
            ));
        }
        let (_, input_index, output, output_index) = attempt.into_parts();
        let written = unsafe {
            // SAFETY: The capacity check above reserves the exact replacement
            // value width, and the hook contract requires encodability.
            self.codec.encode(&value, output, output_index)
        }
        .map_err(|error| TranscodeEncodeError::domain_main(error, input_index))?;
        assert!(
            written == required,
            "Codec::encode wrote a different length than Codec::encode_len",
        );
        Ok(EncodeOutcome::consumed(written))
    }
}

impl<C, H> Default for TranscodeEncodeEngine<C, H>
where
    C: Codec + Default,
    H: TranscodeEncodeHooks<C> + Default,
{
    /// Creates a default buffered encoder engine.
    ///
    /// # Returns
    ///
    /// Returns an engine with default codec and hooks.
    #[inline]
    fn default() -> Self {
        Self::new(C::default(), H::default())
    }
}

impl<C, H> Transcoder for TranscodeEncodeEngine<C, H>
where
    C: Codec,
    H: TranscodeEncodeHooks<C>,
{
    /// Logical values borrowed from the caller during encoding.
    type Input = C::Value;
    /// Encoded storage units written into caller-owned buffers.
    type Output = C::Unit;
    /// Framework failures or codec-domain errors from encoding.
    type Error = TranscodeEncodeErrorOf<C>;

    /// Gets a conservative upper bound for output units needed for
    /// `input_len` values.
    ///
    /// This bound covers only the streaming encode phase. It is delegated to
    /// [`TranscodeEncodeHooks::max_transcode_output_len`], so it includes hook
    /// policy and is valid for every reachable transient codec and hook state.
    /// Downstream encoders must use this engine-level API for capacity planning
    /// instead of recomputing the bound from [`Codec`] constants.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Number of input values the caller plans to encode.
    ///
    /// # Returns
    ///
    /// Returns a conservative upper bound for output units.
    ///
    /// # Errors
    ///
    /// Returns a capacity error when hook planning overflows.
    #[inline]
    fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        TranscodeEncodeEngine::max_transcode_output_len(self, input_len)
    }

    /// Gets the global maximum output units emitted by stream reset.
    ///
    /// # Returns
    ///
    /// Returns the codec's reset-output upper bound. This query never fails.
    #[inline]
    fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
        TranscodeEncodeEngine::max_reset_output_len(self)
    }

    /// Gets the global maximum output units emitted by finishing codec and hook
    /// state.
    ///
    /// Returns the sum of [`Codec::MAX_ENCODE_FINISH_UNITS`] and the
    /// hook-provided final-output bound. The codec finish portion covers units
    /// written by [`Codec::encode_finish`]; hook implementations must not
    /// include that portion in
    /// [`TranscodeEncodeHooks::max_finish_output_len`]. Both component bounds
    /// cover every reachable transient state.
    ///
    /// # Returns
    ///
    /// Returns the combined codec-finish and hook-finish output bound.
    ///
    /// # Errors
    ///
    /// Returns [`CapacityError::OutputLengthOverflow`] when the sum overflows.
    #[inline]
    fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
        TranscodeEncodeEngine::max_finish_output_len(self)
    }

    /// Resets codec encode state, hook-owned state, and stream-start output.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of reset units written.
    ///
    /// # Errors
    ///
    /// Returns framework errors when the caller provides invalid or
    /// insufficient output capacity. Returns domain errors when codec reset or
    /// hook reset handling fails. Capacity and index failures occur before any
    /// reset state is changed. Once reset execution starts, an error poisons
    /// the engine until a later reset succeeds.
    ///
    /// # Panics
    ///
    /// Panics if the codec reports reset output beyond its declared bound.
    #[inline]
    fn reset(&mut self, output: &mut [C::Unit], output_index: usize) -> Result<usize, TranscodeEncodeErrorOf<C>> {
        TranscodeEncodeEngine::reset(self, output, output_index)
    }

    /// Encodes values into a caller-provided output buffer.
    ///
    /// The engine stops before consuming the next input value when the current
    /// output buffer does not satisfy that value's planned capacity bound.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete input value slice visible to the encoder.
    /// - `input_index`: Absolute input value index where encoding starts.
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns progress describing input values consumed, output units written,
    /// and why encoding stopped.
    ///
    /// # Errors
    ///
    /// Returns framework errors when `input_index` is outside `input` or
    /// `output_index` is outside `output`, and domain errors when codec or
    /// hook processing fails or rejects a value. Returns
    /// [`TranscodeFailure::TranscodeBeforeReset`] when the engine has not
    /// completed its first reset. Returns
    /// [`TranscodeFailure::TranscodeAfterFinish`] when the logical stream was
    /// already finished and has not been reset, or
    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
    /// failed after execution started.
    ///
    /// # Panics
    ///
    /// Panics if the codec violates its declared encode length or hooks
    /// return an unencodable replacement.
    #[inline]
    fn transcode(
        &mut self,
        input: &[C::Value],
        input_index: usize,
        output: &mut [C::Unit],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeEncodeErrorOf<C>> {
        TranscodeEncodeEngine::transcode(self, input, input_index, output, output_index)
    }

    /// Finishes codec and hook-owned output after EOF.
    ///
    /// Finalization first finishes encode-side codec state through
    /// [`Codec::encode_finish`], then lets hook implementations finish their
    /// own retained state. The caller must provide enough output capacity for
    /// [`TranscodeEncodeEngine::max_finish_output_len`], which includes both
    /// the codec finish bound and the hook-owned finish bound.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output unit slice visible to the encoder.
    /// - `output_index`: Absolute output unit index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of units written by finalization.
    ///
    /// # Errors
    ///
    /// Returns framework errors when the caller provides invalid or
    /// insufficient output capacity. Returns domain errors when codec finish or
    /// hook finalization fails. Returns
    /// [`TranscodeFailure::FinishBeforeReset`] when the engine has not
    /// completed its first reset. Returns
    /// [`TranscodeFailure::FinishAfterFinish`] when the logical stream was
    /// already finished and has not been reset, or
    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
    /// failed after execution started. Capacity and index failures occur before
    /// finish execution and remain retryable; later failures poison the engine
    /// until reset succeeds.
    ///
    /// # Panics
    ///
    /// Panics when the codec finish writes beyond
    /// [`Codec::MAX_ENCODE_FINISH_UNITS`] or when the combined codec and hook
    /// finalization writes beyond
    /// [`TranscodeEncodeEngine::max_finish_output_len`].
    #[inline]
    fn finish(&mut self, output: &mut [C::Unit], output_index: usize) -> Result<usize, TranscodeEncodeErrorOf<C>> {
        TranscodeEncodeEngine::finish(self, output, output_index)
    }
}

impl<C, H> TranscodeEncoder for TranscodeEncodeEngine<C, H>
where
    C: Codec,
    H: TranscodeEncodeHooks<C>,
{
    /// Codec-specific source error retained by domain failures.
    type EncodeError = C::EncodeError;
}