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
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Reusable buffered decoder engine.

use core::num::NonZeroUsize;

use super::super::internal::applied_decode_invalid_action::AppliedDecodeInvalidAction;
use super::super::internal::decode_state::DecodeState;
use super::super::internal::lifecycle_guard::LifecycleGuard;
use super::DecodeContext;
use super::DecodeIncompleteAction;
use super::DecodeInvalidAction;
use super::DecodeOutcome;
use super::TranscodeDecodeHooks;
use crate::CapacityError;
use crate::Codec;
use crate::DecodeFailure;
use crate::TranscodeDecodeError;
use crate::TranscodeDecodeErrorOf;
use crate::TranscodeDecoder;
use crate::TranscodeFailure;
use crate::TranscodeProgress;
use crate::Transcoder;
use crate::codec::assert_unit_bounds;

/// Reusable buffered decoding engine for codec-backed decoders.
///
/// The engine owns the low-level codec and hook object. It keeps the common
/// buffered decoding loop private: input-index validation, output-capacity
/// checks, calls to [`Codec::decode`], hook dispatch, and
/// [`crate::TranscodeStatus`] reporting. Incomplete input tails are left in the
/// caller-provided input slice; callers own input-buffer refill.
///
/// Use this type to build a streaming decoder over a one-value [`Codec`]. The
/// engine decodes into a caller-provided output slice and returns
/// [`TranscodeProgress`] instead of allocating. On success it writes decoded
/// values directly to output. On codec errors it delegates to
/// [`crate::engine::TranscodeDecodeHooks`], allowing a policy to skip invalid
/// units, emit a replacement value, or fail.
///
/// The engine stops before reading an incomplete value when fewer than
/// [`Codec::MIN_UNITS_PER_VALUE`] units are available. For variable-width
/// codecs, the codec may still return an incomplete decode error after that
/// minimum is satisfied. Both conditions return
/// [`crate::TranscodeStatus::NeedInput`] while the stream is open; at EOF the
/// hook selects whether to reject, skip, or replace the remaining tail.
///
/// For strict decoding that wraps codec errors, use
/// [`crate::CodecTranscodeDecoder`]. Use `TranscodeDecodeEngine` directly when
/// invalid input should be repaired, skipped, counted, or otherwise handled by
/// policy.
///
/// # Examples
///
/// ```rust
/// use core::num::NonZeroUsize;
/// use qubit_codec::{
///     Codec,
///     TranscodeDecodeErrorOf,
///     DecodeFailure,
///     TranscodeStatus,
/// };
/// use qubit_codec::engine::{
///     DecodeContext,
///     DecodeInvalidAction,
///     TranscodeDecodeEngine,
///     TranscodeDecodeHooks,
/// };
///
/// #[derive(Clone, Copy)]
/// struct ByteCodec;
///
/// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// enum ByteDecodeError {
///     Malformed { consumed: NonZeroUsize },
/// }
///
/// impl Codec for ByteCodec {
///     type Value = u8;
///     type Unit = u8;
///     type DecodeError = ByteDecodeError;
///     type EncodeError = core::convert::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>> {
///         match input[index] {
///             0xff => Err(DecodeFailure::invalid(
///                 ByteDecodeError::Malformed {
///                     consumed: NonZeroUsize::MIN,
///                 },
///                 NonZeroUsize::MIN,
///             )),
///             value => Ok((value, NonZeroUsize::MIN)),
///         }
///     }
///
///     unsafe fn encode(
///         &mut self,
///         value: &u8,
///         output: &mut [u8],
///         index: usize,
///     ) -> Result<usize, Self::EncodeError> {
///         output[index] = *value;
///         Ok(1)
///     }
/// }
///
/// struct ReplacementHooks;
///
/// impl TranscodeDecodeHooks<ByteCodec> for ReplacementHooks {
///     fn handle_invalid_decode(
///         &mut self,
///         _codec: &mut ByteCodec,
///         error: &ByteDecodeError,
///         consumed: Option<NonZeroUsize>,
///         _context: DecodeContext,
///     ) -> Result<DecodeInvalidAction<u8>, TranscodeDecodeErrorOf<ByteCodec>> {
///         match error {
///             ByteDecodeError::Malformed { .. } => {
///                 Ok(DecodeInvalidAction::Emit {
///                     value: b'?',
///                     consumed: consumed.expect("codec reported malformed width"),
///                 })
///             }
///         }
///     }
/// }
///
/// let mut engine = TranscodeDecodeEngine::<_, _>::new(ByteCodec, ReplacementHooks);
/// let input = [b'a', 0xff, b'b'];
/// let mut output = [0_u8; 3];
/// let mut reset_output = [];
/// engine.reset(&mut reset_output, 0)?;
///
/// let progress = engine.transcode(&input, 0, &mut output, 0)?;
/// match progress.status() {
///     TranscodeStatus::Complete => assert_eq!(&output[..progress.written()], b"a?b"),
///     TranscodeStatus::NeedInput { .. } => {
///         // Keep `input[input_index + progress.read()..]`, append more source
///         // units, and resume.
///     }
///     TranscodeStatus::NeedOutput { .. } => {
///         // Drain `output[..progress.written()]`, then resume with more output
///         // room.
///     }
/// }
/// # Ok::<(), qubit_codec::TranscodeDecodeError<ByteDecodeError>>(())
/// ```
///
/// # Type Parameters
///
/// - `C`: Low-level codec used by the engine.
/// - `H`: Policy hook object used by the engine.
#[derive(Debug)]
pub struct TranscodeDecodeEngine<C, H> {
    /// Low-level codec used for one-value decoding.
    pub(super) codec: C,
    /// Policy hooks used for decode failures.
    pub(super) hooks: H,
    /// Guard for the `reset → transcode* → finish` lifecycle in every build
    /// profile.
    lifecycle: LifecycleGuard,
}

impl<C, H> Default for TranscodeDecodeEngine<C, H>
where
    C: Codec + Default,
    H: TranscodeDecodeHooks<C> + Default,
{
    /// Creates an engine with the same codec-bound checks as [`Self::new`].
    ///
    /// # Returns
    ///
    /// Returns a fresh engine containing default codec and hook values.
    ///
    /// # Compile-Time Checks
    ///
    /// Fails to compile when the codec declares a zero decode unit bound or
    /// when [`Codec::MIN_UNITS_PER_VALUE`] exceeds
    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], matching [`Self::new`].
    ///
    /// A legal codec and hook can use the default constructor:
    ///
    /// ```rust
    /// use core::convert::Infallible;
    /// use core::num::NonZeroUsize;
    /// use qubit_codec::{Codec, DecodeFailure};
    /// use qubit_codec::engine::{DecodeContext, DecodeInvalidAction, TranscodeDecodeEngine, TranscodeDecodeHooks};
    ///
    /// #[derive(Default)]
    /// 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)
    ///     }
    /// }
    /// #[derive(Default)]
    /// struct Hooks;
    /// impl TranscodeDecodeHooks<ByteCodec> for Hooks {
    ///     fn handle_invalid_decode(&mut self, _codec: &mut ByteCodec, error: &Infallible, _consumed: Option<NonZeroUsize>, _context: DecodeContext) -> Result<DecodeInvalidAction<u8>, qubit_codec::TranscodeDecodeError<Infallible>> {
    ///         match *error {}
    ///     }
    /// }
    /// let _engine = TranscodeDecodeEngine::<ByteCodec, Hooks>::default();
    /// ```
    ///
    /// A zero minimum decode bound is rejected:
    ///
    /// ```compile_fail
    /// use core::convert::Infallible;
    /// use core::num::NonZeroUsize;
    /// use qubit_codec::{Codec, DecodeFailure};
    /// use qubit_codec::engine::{DecodeContext, DecodeInvalidAction, TranscodeDecodeEngine, TranscodeDecodeHooks};
    /// #[derive(Default)] struct BadCodec;
    /// impl Codec for BadCodec {
    ///     type Value = u8; type Unit = u8; type DecodeError = Infallible; type EncodeError = Infallible;
    ///     const MIN_UNITS_PER_VALUE: usize = 0; 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) }
    /// }
    /// #[derive(Default)] struct Hooks;
    /// impl TranscodeDecodeHooks<BadCodec> for Hooks {
    ///     fn handle_invalid_decode(&mut self, _codec: &mut BadCodec, error: &Infallible, _consumed: Option<NonZeroUsize>, _context: DecodeContext) -> Result<DecodeInvalidAction<u8>, qubit_codec::TranscodeDecodeError<Infallible>> { match *error {} }
    /// }
    /// let _ = TranscodeDecodeEngine::<BadCodec, Hooks>::default();
    /// ```
    ///
    /// A minimum larger than the maximum decode width is also rejected:
    ///
    /// ```compile_fail
    /// use core::convert::Infallible;
    /// use core::num::NonZeroUsize;
    /// use qubit_codec::{Codec, DecodeFailure};
    /// use qubit_codec::engine::{DecodeContext, DecodeInvalidAction, TranscodeDecodeEngine, TranscodeDecodeHooks};
    /// #[derive(Default)] struct BadCodec;
    /// impl Codec for BadCodec {
    ///     type Value = u8; type Unit = u8; type DecodeError = Infallible; type EncodeError = Infallible;
    ///     const MIN_UNITS_PER_VALUE: usize = 2; 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) }
    /// }
    /// #[derive(Default)] struct Hooks;
    /// impl TranscodeDecodeHooks<BadCodec> for Hooks {
    ///     fn handle_invalid_decode(&mut self, _codec: &mut BadCodec, error: &Infallible, _consumed: Option<NonZeroUsize>, _context: DecodeContext) -> Result<DecodeInvalidAction<u8>, qubit_codec::TranscodeDecodeError<Infallible>> { match *error {} }
    /// }
    /// let _ = TranscodeDecodeEngine::<BadCodec, Hooks>::default();
    /// ```
    #[inline]
    fn default() -> Self {
        Self::new(C::default(), H::default())
    }
}

/// Adds two independent decoded-value capacity bounds.
///
/// # Parameters
///
/// - `first`: First decoded-value bound.
/// - `second`: Independent decoded-value bound to add.
///
/// # Returns
///
/// Returns the combined decoded-value bound.
///
/// # Errors
///
/// Returns `CapacityError::OutputLengthOverflow` if the sum exceeds
/// `usize::MAX`.
#[inline]
fn add_decode_output_bounds(first: usize, second: usize) -> Result<usize, CapacityError> {
    first.checked_add(second).ok_or(CapacityError::OutputLengthOverflow)
}

/// Adds reset, transcode, and finish decoded-value capacity bounds.
///
/// # Parameters
///
/// - `reset`: Maximum reset output.
/// - `transcode`: Maximum streaming output.
/// - `finish`: Maximum finalization output.
///
/// # Returns
///
/// Returns the complete-stream decoded-value bound.
///
/// # Errors
///
/// Returns `CapacityError::OutputLengthOverflow` if the sum exceeds
/// `usize::MAX`.
#[inline]
fn sum_decode_output_bounds(reset: usize, transcode: usize, finish: usize) -> Result<usize, CapacityError> {
    let before_finish = add_decode_output_bounds(reset, transcode)?;
    add_decode_output_bounds(before_finish, finish)
}

impl<C, H> TranscodeDecodeEngine<C, H>
where
    C: Codec,
    H: TranscodeDecodeHooks<C>,
{
    /// Creates a buffered decoder engine.
    ///
    /// # Parameters
    ///
    /// - `codec`: Low-level codec used for one-value decoding.
    /// - `hooks`: Policy hooks used for decode failures.
    ///
    /// # Returns
    ///
    /// Returns a buffered decoder 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`].
    #[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]
    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]
    pub fn codec_mut(&mut self) -> &mut C {
        &mut self.codec
    }

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

    /// Returns the decode hooks mutably.
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to the hook object owned by this engine.
    #[inline]
    #[must_use]
    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 decode hooks.
    #[inline]
    #[must_use]
    pub fn into_parts(self) -> (C, H) {
        let Self { codec, hooks, .. } = self;
        (codec, hooks)
    }

    /// Returns an upper bound for decoded values produced from `input_len`
    /// units.
    ///
    /// This bound covers only the streaming decode phase. It is delegated to
    /// [`TranscodeDecodeHooks::max_transcode_output_len`], so it includes hook
    /// policy and is valid for every reachable transient codec and hook state.
    /// Downstream decoders must use this engine-level API for capacity planning
    /// instead of recomputing the bound from [`Codec`] constants.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Number of source units the caller plans to decode.
    ///
    /// # Returns
    ///
    /// Returns a conservative upper bound, or a capacity error on arithmetic
    /// overflow.
    ///
    /// # Errors
    ///
    /// Returns a capacity error when hook capacity arithmetic overflows.
    #[inline]
    #[must_use = "capacity planning can fail on overflow"]
    pub fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        self.hooks.max_transcode_output_len(&self.codec, input_len)
    }

    /// Returns the global maximum values emitted by finishing codec state and
    /// finishing hook-owned state.
    ///
    /// # Returns
    ///
    /// Returns the sum of [`Codec::MAX_DECODE_FINISH_VALUES`] and the
    /// hook-provided final-output bound. The codec finish portion covers values
    /// written by [`Codec::decode_finish`]; hook implementations must not
    /// include that portion in
    /// [`TranscodeDecodeHooks::max_finish_output_len`]. Both component bounds
    /// cover every reachable transient state.
    ///
    /// # Errors
    ///
    /// Returns a capacity error when the combined finish bound exceeds
    /// `usize::MAX`.
    #[inline]
    #[must_use = "capacity planning can fail on overflow"]
    pub fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
        add_decode_output_bounds(
            C::MAX_DECODE_FINISH_VALUES,
            self.hooks.max_finish_output_len(&self.codec),
        )
    }

    /// Returns the global maximum values emitted when resetting stream state.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Codec::MAX_DECODE_RESET_VALUES)` for the wrapped codec.
    /// This query cannot fail.
    /// Stateless decoders always return `0`.
    #[inline]
    pub fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
        Ok(C::MAX_DECODE_RESET_VALUES)
    }

    /// Returns the maximum values needed by a complete one-shot decode stream.
    ///
    /// The returned bound covers reset output, the streaming decode phase for
    /// `input_len` units, and finish output. Its components are global across
    /// transient state. Higher-level complete decode 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 source units in the complete stream.
    ///
    /// # Returns
    ///
    /// Returns the complete-stream output bound, or a capacity error on
    /// arithmetic overflow.
    ///
    /// # Errors
    ///
    /// Returns a capacity error when a component or their sum overflows.
    #[inline]
    #[must_use = "capacity planning can fail on overflow"]
    pub fn max_total_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        let transcode = self.max_transcode_output_len(input_len)?;
        let finish = self.max_finish_output_len()?;
        sum_decode_output_bounds(C::MAX_DECODE_RESET_VALUES, transcode, finish)
    }

    /// Resets codec decode state, runs reset hooks, and emits stream-start
    /// values.
    ///
    /// The sequence is: validate capacity → run `reset_hooks` → call
    /// [`Codec::decode_reset`]. Stateless decoders (`MAX_DECODE_RESET_VALUES
    /// == 0`) write nothing and return `Ok(0)`.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output value slice visible to the decoder.
    /// - `output_index`: Absolute output value index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of reset values 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 more than `MAX_DECODE_RESET_VALUES` written.
    pub fn reset(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
        let required = C::MAX_DECODE_RESET_VALUES;
        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.decode_reset(output, output_index)
        }
        .map_err(TranscodeDecodeError::domain_reset)?;
        assert!(written <= required, "Codec::decode_reset wrote beyond its reset bound",);
        self.lifecycle.on_reset_success();
        Ok(written)
    }

    /// Decodes source units into caller-provided output values.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete input unit slice visible to the decoder.
    /// - `input_index`: Absolute input unit index where decoding starts.
    /// - `output`: Complete output value slice visible to the decoder.
    /// - `output_index`: Absolute output value index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns progress describing input units consumed, output values written,
    /// and why decoding stopped.
    ///
    /// # Errors
    ///
    /// Returns framework errors when either index is outside its slice, and
    /// domain errors when a concrete policy hook 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 when codec or hook progress violates declared decode bounds.
    #[inline]
    pub fn transcode(
        &mut self,
        input: &[C::Unit],
        input_index: usize,
        output: &mut [C::Value],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
        self.transcode_with_eof(input, input_index, output, output_index, false)
    }

    /// Decodes source units after the caller has established end of input.
    ///
    /// This follows the normal streaming contract, except that codec attempts
    /// use [`Codec::decode_eof`]. A codec may therefore resolve a trailing
    /// prefix that would remain incomplete in an open stream.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete source-unit slice.
    /// - `input_index`: Absolute index of the next source unit.
    /// - `output`: Destination for decoded values.
    /// - `output_index`: Absolute index of the next destination slot.
    ///
    /// # Returns
    ///
    /// Returns consumed/written counts and the reason decoding stopped.
    ///
    /// # Errors
    ///
    /// At confirmed EOF, an incomplete tail requires one writable output slot
    /// before the incomplete-input hook runs, including when that hook might
    /// skip or reject. A capacity shortage leaves both the tail and hook state
    /// untouched; errors after hook execution do not roll back hook mutations.
    ///
    /// Returns framework errors for invalid lifecycle state or slice indices,
    /// and policy/domain errors for rejected input, including incomplete EOF
    /// tails.
    ///
    /// # Panics
    ///
    /// Panics when codec or hook progress violates declared decode bounds.
    #[inline]
    pub fn transcode_eof(
        &mut self,
        input: &[C::Unit],
        input_index: usize,
        output: &mut [C::Value],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
        self.transcode_with_eof(input, input_index, output, output_index, true)
    }

    /// Finishes codec and hook-owned output after EOF.
    ///
    /// Finalization first finishes decode-side codec state through
    /// [`Codec::decode_finish`], then lets hook implementations finish their
    /// own retained state. The caller must provide enough output capacity for
    /// [`TranscodeDecodeEngine::max_finish_output_len`], which includes both
    /// the codec finish bound and the hook-owned finish bound.
    ///
    /// # Parameters
    ///
    /// - `output`: Complete output value slice visible to the decoder.
    /// - `output_index`: Absolute output value index where writing starts.
    ///
    /// # Returns
    ///
    /// Returns the number of values 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::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
        self.lifecycle.on_finish_attempt()?;
        let hook_required = self.hooks.max_finish_output_len(&self.codec);
        let required = C::MAX_DECODE_FINISH_VALUES
            .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 { self.codec.decode_finish(output, output_index) }.map_err(TranscodeDecodeError::domain_finish)?;
        assert!(
            finished <= C::MAX_DECODE_FINISH_VALUES,
            "Codec::decode_finish wrote beyond its finish bound",
        );
        let written = self
            .hooks
            .finish_hooks(&mut self.codec, output, output_index + finished)?;
        assert!(
            written <= hook_required,
            "TranscodeDecodeEngine hook wrote beyond its finish bound",
        );
        self.lifecycle.on_finish_success();
        Ok(finished + written)
    }

    /// Runs a complete one-shot `reset -> transcode -> finish` decode 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 decoder
    /// helpers should call this engine method instead of reproducing the
    /// reset, transcode, and finish sequence themselves.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete source unit slice.
    /// - `output`: Output value slice for the whole decoded stream.
    ///
    /// # Returns
    ///
    /// Returns the number of output values written.
    ///
    /// # Errors
    ///
    /// Returns framework errors for insufficient output, capacity overflow, or
    /// an incomplete EOF tail, and domain errors from reset, decode, or
    /// finish.
    ///
    /// # Panics
    ///
    /// Panics when codec or hook output violates reset, decode, or finish
    /// bounds.
    #[inline]
    pub fn transcode_complete_into(
        &mut self,
        input: &[C::Unit],
        output: &mut [C::Value],
    ) -> Result<usize, TranscodeDecodeErrorOf<C>> {
        <Self as Transcoder>::transcode_complete_into(self, input, output)
    }

    /// Decodes one source value attempt and delivers emitted values.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete input unit slice visible to the caller.
    /// - `context`: Decode context describing the current source and output
    ///   cursors.
    /// - `end_of_input`: Whether the source is final and EOF policy applies.
    /// - `consume`: Callback invoked exactly once when this attempt emits a
    ///   logical value.
    ///
    /// # Type Parameters
    ///
    /// - `R`: Value returned by the consumer when a decoded value is emitted.
    /// - `F`: Consumer callback type.
    ///
    /// # Returns
    ///
    /// Returns the decode outcome and `Some` consumer result when a value was
    /// emitted; returns `None` when input was skipped or more input is needed.
    ///
    /// # Errors
    ///
    /// Returns hook errors when the decode policy rejects the input.
    ///
    /// # Panics
    ///
    /// Panics when the codec reports consumption beyond the available input,
    /// an incomplete-input requirement beyond
    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], or hooks return an action that
    /// consumes beyond the available input. Also panics when reported consumed
    /// width exceeds the codec maximum or an incomplete requirement does not
    /// exceed available input. Debug builds reject an empty context.
    pub(crate) fn decode_one<R, F>(
        &mut self,
        input: &[C::Unit],
        context: DecodeContext,
        end_of_input: bool,
        consume: F,
    ) -> Result<(DecodeOutcome, Option<R>), TranscodeDecodeErrorOf<C>>
    where
        F: FnOnce(C::Value, usize) -> R,
    {
        debug_assert!(
            context.available() > 0,
            "decode_one requires at least one source input unit",
        );

        if context.available() < C::MIN_UNITS_PER_VALUE {
            let required_total =
                NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
            if !end_of_input {
                return Ok((DecodeOutcome::need_input(required_total), None));
            }
            return self.apply_incomplete_decode(None, required_total, context, consume);
        }

        // SAFETY: The context reports at least `MIN_UNITS_PER_VALUE` source
        // units available from `context.input_index()`.
        let result = unsafe {
            if end_of_input {
                self.codec.decode_eof(input, context.input_index())
            } else {
                self.codec.decode(input, context.input_index())
            }
        };
        match result {
            Ok((value, consumed)) => {
                assert!(
                    consumed.get() <= context.available(),
                    "Codec::decode consumed beyond available input",
                );
                assert!(
                    consumed.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
                    "Codec::decode consumed beyond Codec::MAX_DECODE_UNITS_PER_VALUE",
                );
                let consumed_value = consume(value, context.input_index());
                Ok((
                    DecodeOutcome::emitted(consumed, NonZeroUsize::MIN),
                    Some(consumed_value),
                ))
            }
            Err(DecodeFailure::Incomplete { source, required_total }) => {
                assert!(
                    required_total.get() > context.available(),
                    "Codec::decode incomplete required_total must exceed available input",
                );
                assert!(
                    required_total.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
                    "Codec::decode incomplete required_total exceeded Codec::MAX_DECODE_UNITS_PER_VALUE",
                );
                if !end_of_input {
                    return Ok((DecodeOutcome::need_input(required_total), None));
                }
                self.apply_incomplete_decode(source, required_total, context, consume)
            }
            Err(DecodeFailure::Invalid { source, consumed }) => {
                let action = match self
                    .hooks
                    .handle_invalid_decode(&mut self.codec, &source, consumed, context)?
                {
                    DecodeInvalidAction::Reject => {
                        return Err(TranscodeDecodeError::domain_main_with_consumed(
                            source,
                            context.input_index(),
                            consumed,
                        ));
                    }
                    DecodeInvalidAction::Skip { consumed } => AppliedDecodeInvalidAction::Skip { consumed },
                    DecodeInvalidAction::Emit { value, consumed } => {
                        AppliedDecodeInvalidAction::Emit { value, consumed }
                    }
                };
                Ok(Self::apply_invalid_decode_action(action, context, consume))
            }
        }
    }

    /// Runs one decode step with an explicit end-of-input flag.
    ///
    /// The helper centralizes lifecycle validation and shared cursor handling
    /// for the streaming and EOF-aware entry points.
    ///
    /// # Parameters
    ///
    /// - `input`: Complete source-unit slice.
    /// - `input_index`: Absolute index of the next source unit.
    /// - `output`: Destination for decoded values.
    /// - `output_index`: Absolute index of the next destination slot.
    /// - `end_of_input`: Whether to resolve incomplete tails through EOF
    ///   policy.
    ///
    /// # Returns
    ///
    /// Returns consumed/written counts and the reason decoding stopped.
    ///
    /// # Errors
    ///
    /// Returns framework errors for invalid lifecycle state or slice indices,
    /// and policy/domain errors for rejected input, including incomplete EOF
    /// tails.
    ///
    /// # Panics
    ///
    /// Panics when codec or hook progress violates declared decode bounds.
    fn transcode_with_eof(
        &mut self,
        input: &[C::Unit],
        input_index: usize,
        output: &mut [C::Value],
        output_index: usize,
        end_of_input: bool,
    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
        self.lifecycle.on_transcode()?;
        TranscodeFailure::ensure_transcode_indices(input.len(), input_index, output.len(), output_index)?;

        let min_units = NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
        let min_units_len = min_units.get();
        let mut state = DecodeState::new(input, input_index, output, output_index);
        while state.has_input() {
            let context = state.context();
            let available = context.available();
            if available < min_units_len {
                if !end_of_input {
                    return Ok(state.need_input_progress_with(min_units));
                }
                if state.needs_output() {
                    return Ok(state.need_output_progress());
                }
                let output_index = state.output_cursor();
                let output = state.output_mut();
                let (outcome, _) = self.decode_one(input, context, true, |value, _input_index| {
                    // SAFETY: The empty-output check above proved this slot writable.
                    unsafe {
                        *output.get_unchecked_mut(output_index) = value;
                    }
                })?;
                if let Some(progress) = state.apply_decode_outcome(outcome) {
                    return Ok(progress);
                }
                continue;
            }
            if state.needs_output() {
                return Ok(state.need_output_progress());
            }
            let output_index = state.output_cursor();
            let output = state.output_mut();
            let (outcome, _) = self.decode_one(input, context, end_of_input, |value, _input_index| {
                // SAFETY: `needs_output()` returned false, so the output
                // cursor points at a writable initialized slot.
                unsafe {
                    *output.get_unchecked_mut(output_index) = value;
                }
            })?;
            if let Some(progress) = state.apply_decode_outcome(outcome) {
                return Ok(progress);
            }
        }

        Ok(state.complete_progress())
    }

    /// Applies a hook-selected invalid-decode action after reject handling.
    ///
    /// # Type Parameters
    ///
    /// - `R`: Consumer result for an emitted value.
    /// - `F`: Callback consuming an emitted value and its source index.
    ///
    /// # Parameters
    ///
    /// - `action`: Validated policy action to skip or emit.
    /// - `context`: Source cursor and available input.
    /// - `consume`: Callback invoked only for an emitted value.
    ///
    /// # Returns
    ///
    /// Returns progress with `Some` callback result for Emit, or `None` for
    /// Skip.
    ///
    /// # Panics
    ///
    /// Panics if the action consumes more units than the context makes
    /// available.
    fn apply_invalid_decode_action<R, F>(
        action: AppliedDecodeInvalidAction<C::Value>,
        context: DecodeContext,
        consume: F,
    ) -> (DecodeOutcome, Option<R>)
    where
        F: FnOnce(C::Value, usize) -> R,
    {
        match action {
            AppliedDecodeInvalidAction::Skip { consumed } => {
                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
                (DecodeOutcome::skipped(read), None)
            }
            AppliedDecodeInvalidAction::Emit { value, consumed } => {
                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
                let consumed_value = consume(value, context.input_index());
                (DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(consumed_value))
            }
        }
    }

    /// Applies the hook policy to an incomplete input tail.
    ///
    /// # Type Parameters
    ///
    /// - `R`: Consumer result for an emitted value.
    /// - `F`: Callback used to consume an emitted value and its source index.
    ///
    /// # Parameters
    ///
    /// - `source`: Optional codec error associated with the incomplete tail.
    /// - `required_total`: Minimum total input width needed to decode a value.
    /// - `context`: Decode cursors and the number of visible source units.
    /// - `consume`: Callback used once when the policy emits a value.
    ///
    /// # Returns
    ///
    /// Returns the decode outcome and `Some` consumer result when the policy
    /// emits a value; returns `None` when it skips the incomplete tail.
    ///
    /// # Errors
    ///
    /// Returns the hook error or the appropriate incomplete-input rejection,
    /// preserving a codec error source when one was supplied.
    fn apply_incomplete_decode<R, F>(
        &mut self,
        source: Option<C::DecodeError>,
        required_total: NonZeroUsize,
        context: DecodeContext,
        consume: F,
    ) -> Result<(DecodeOutcome, Option<R>), TranscodeDecodeErrorOf<C>>
    where
        F: FnOnce(C::Value, usize) -> R,
    {
        match self
            .hooks
            .handle_incomplete_decode(&mut self.codec, source.as_ref(), required_total, context)?
        {
            DecodeIncompleteAction::Reject => match source {
                Some(source) => Err(TranscodeDecodeError::domain_main(source, context.input_index())),
                None => Err(TranscodeFailure::incomplete_input(
                    context.input_index(),
                    required_total.get(),
                    context.available(),
                )
                .into()),
            },
            DecodeIncompleteAction::Skip => {
                let read =
                    NonZeroUsize::new(context.available()).expect("incomplete decode tail must contain source units");
                Ok((DecodeOutcome::skipped(read), None))
            }
            DecodeIncompleteAction::Emit { value } => {
                let read =
                    NonZeroUsize::new(context.available()).expect("incomplete decode tail must contain source units");
                let result = consume(value, context.input_index());
                Ok((DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(result)))
            }
        }
    }
}

impl<C, H> Transcoder for TranscodeDecodeEngine<C, H>
where
    C: Codec,
    H: TranscodeDecodeHooks<C>,
{
    /// Source units accepted by the wrapped codec.
    type Input = C::Unit;
    /// Logical values decoded by the wrapped codec.
    type Output = C::Value;
    /// Framework failures and the wrapped codec's decode errors.
    type Error = TranscodeDecodeErrorOf<C>;

    /// Returns an upper bound for decoded values produced from `input_len`
    /// units.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Number of source units to decode.
    ///
    /// # Returns
    ///
    /// Returns the conservative streaming output bound.
    ///
    /// # Errors
    ///
    /// Returns a capacity error on hook arithmetic overflow.
    #[inline]
    fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
        TranscodeDecodeEngine::max_transcode_output_len(self, input_len)
    }

    /// Returns an upper bound for values produced by finishing codec and hook
    /// state.
    ///
    /// # Returns
    ///
    /// Returns the combined codec and hook finish bound.
    ///
    /// # Errors
    ///
    /// Returns a capacity error if that sum overflows.
    #[inline]
    fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
        TranscodeDecodeEngine::max_finish_output_len(self)
    }

    /// Returns an upper bound for values emitted when resetting stream state.
    ///
    /// # Returns
    ///
    /// Returns the codec reset bound as `Ok`; this query cannot fail.
    #[inline]
    fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
        TranscodeDecodeEngine::max_reset_output_len(self)
    }

    /// Resets hooks and codec state, emitting any stream-start values.
    ///
    /// # Parameters
    ///
    /// - `output`: Destination value slice.
    /// - `output_index`: First writable value index.
    ///
    /// # Returns
    ///
    /// Returns the number of stream-start values written.
    ///
    /// # Errors
    ///
    /// Returns invalid-capacity/index errors or codec reset domain errors.
    ///
    /// # Panics
    ///
    /// Panics if codec reset output exceeds its declared bound.
    fn reset(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
        TranscodeDecodeEngine::reset(self, output, output_index)
    }

    /// Decodes source units into logical values.
    ///
    /// # Parameters
    ///
    /// - `input`: Source unit slice.
    /// - `input_index`: First source index.
    /// - `output`: Destination value slice.
    /// - `output_index`: First destination index.
    ///
    /// # Returns
    ///
    /// Returns consumed/written counts and the stop status.
    ///
    /// # Errors
    ///
    /// Returns lifecycle/index errors or rejected-input domain errors.
    ///
    /// # Panics
    ///
    /// Panics if codec or hook progress violates decode bounds.
    fn transcode(
        &mut self,
        input: &[C::Unit],
        input_index: usize,
        output: &mut [C::Value],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
        TranscodeDecodeEngine::transcode(self, input, input_index, output, output_index)
    }

    /// Decodes source units after end of input is known.
    ///
    /// # Parameters
    ///
    /// - `input`: Final source unit slice.
    /// - `input_index`: First source index.
    /// - `output`: Destination value slice.
    /// - `output_index`: First destination index.
    ///
    /// # Returns
    ///
    /// Returns consumed/written counts and the stop status.
    ///
    /// # Errors
    ///
    /// Returns lifecycle/index errors or rejected input and incomplete-tail
    /// errors.
    ///
    /// # Panics
    ///
    /// Panics if codec or hook progress violates decode bounds.
    fn transcode_eof(
        &mut self,
        input: &[C::Unit],
        input_index: usize,
        output: &mut [C::Value],
        output_index: usize,
    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
        TranscodeDecodeEngine::transcode_eof(self, input, input_index, output, output_index)
    }

    /// Finishes internally retained output after EOF.
    ///
    /// # Parameters
    ///
    /// - `output`: Destination value slice.
    /// - `output_index`: First writable value index.
    ///
    /// # Returns
    ///
    /// Returns the number of final values written.
    ///
    /// # Errors
    ///
    /// Returns lifecycle/capacity/index errors or codec/hook finish errors.
    ///
    /// # Panics
    ///
    /// Panics if finalization output exceeds its declared bounds.
    fn finish(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
        TranscodeDecodeEngine::finish(self, output, output_index)
    }
}

impl<C, H> TranscodeDecoder for TranscodeDecodeEngine<C, H>
where
    C: Codec,
    H: TranscodeDecodeHooks<C>,
{
    /// Domain error reported by the wrapped codec while decoding.
    type DecodeError = C::DecodeError;
}