qubit_codec/transcode/engine/transcode_encode_hooks.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Policy hooks used by buffered encoder engines.
9
10use super::encode_context::EncodeContext;
11use super::encode_unencodable_action::EncodeUnencodableAction;
12use crate::CapacityError;
13use crate::Codec;
14use crate::TranscodeEncodeErrorOf;
15
16/// Policy hooks for [`crate::engine::TranscodeEncodeEngine`].
17///
18/// Hooks own policy state, such as replacement or ignore behavior, but not the
19/// codec or engine cursor state. The engine owns the normal one-value encode
20/// operation and calls hooks only when policy decisions are needed.
21///
22/// Implement this trait when a buffered encoder needs policy decisions around
23/// individual values while reusing the common engine loop. Examples include
24/// rejecting unsupported values with adapter-level context, skipping
25/// unsupported values, replacing them with encodable values, resetting
26/// hook-owned state in [`reset_hooks`](Self::reset_hooks), or emitting final
27/// state in [`finish_hooks`](Self::finish_hooks).
28///
29/// The engine calls
30/// [`handle_unencodable_encode`](Self::handle_unencodable_encode) only after
31/// [`Codec::can_encode_value`] returns `false` for the current input
32/// value. Encodable values are encoded directly by the engine with
33/// [`Codec::encode_len`] and [`Codec::encode`].
34///
35/// # Examples
36///
37/// This hook reports unsupported values as adapter-level errors.
38///
39/// ```rust
40/// use core::convert::Infallible;
41/// use core::num::NonZeroUsize;
42///
43/// use qubit_codec::Codec;
44/// use qubit_codec::DecodeFailure;
45/// use qubit_codec::TranscodeEncodeErrorOf;
46/// use qubit_codec::engine::EncodeContext;
47/// use qubit_codec::engine::EncodeUnencodableAction;
48/// use qubit_codec::engine::TranscodeEncodeEngine;
49/// use qubit_codec::engine::TranscodeEncodeHooks;
50///
51/// #[derive(Clone, Copy)]
52/// struct ByteCodec;
53///
54/// impl Codec for ByteCodec {
55/// type Value = u8;
56/// type Unit = u8;
57/// type DecodeError = Infallible;
58/// type EncodeError = Infallible;
59///
60/// const MIN_UNITS_PER_VALUE: usize = 1;
61/// const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
62/// const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
63///
64/// unsafe fn decode(
65/// &mut self,
66/// input: &[u8],
67/// index: usize,
68/// ) -> Result<(u8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
69/// Ok((input[index], NonZeroUsize::MIN))
70/// }
71///
72/// unsafe fn encode(
73/// &mut self,
74/// value: &u8,
75/// output: &mut [u8],
76/// index: usize,
77/// ) -> Result<usize, Self::EncodeError> {
78/// output[index] = *value;
79/// Ok(1)
80/// }
81/// }
82///
83/// struct StrictHooks;
84///
85/// impl<C> TranscodeEncodeHooks<C> for StrictHooks
86/// where
87/// C: Codec,
88/// {
89/// fn handle_unencodable_encode(
90/// &mut self,
91/// _codec: &mut C,
92/// _context: &EncodeContext<'_, C::Value>,
93/// ) -> Result<EncodeUnencodableAction<C::Value>, TranscodeEncodeErrorOf<C>> {
94/// Ok(EncodeUnencodableAction::Reject)
95/// }
96/// }
97///
98/// let mut engine = TranscodeEncodeEngine::new(ByteCodec, StrictHooks);
99/// engine.reset(&mut [], 0).unwrap();
100/// let mut output = [0_u8; 1];
101/// let progress = engine.transcode(&[42], 0, &mut output, 0).unwrap();
102/// assert_eq!(progress.read(), 1);
103/// assert_eq!(progress.written(), 1);
104/// assert_eq!(output, [42]);
105/// ```
106///
107/// # Type Parameters
108///
109/// - `C`: Low-level codec owned by the engine.
110pub trait TranscodeEncodeHooks<C>
111where
112 C: Codec,
113{
114 /// Returns the maximum output units needed for `input_len` values.
115 ///
116 /// This bound covers only the streaming encode phase driven by
117 /// [`crate::engine::TranscodeEncodeEngine::transcode`]. It must not include
118 /// codec reset output, codec finish output, or hook finish output.
119 /// It may depend on immutable hook and codec configuration, but it must
120 /// cover every reachable transient hook and codec state, including the
121 /// maximum hook-owned pending output that may be drained during transcode.
122 ///
123 /// The default implementation multiplies `input_len` by
124 /// [`Codec::MAX_ENCODE_UNITS_PER_VALUE`]. This bound is valid for direct
125 /// encoding, skipped unencodable values, and single-value replacements.
126 /// Override it only when hook-owned pending output can be drained
127 /// during `transcode`.
128 ///
129 /// # Parameters
130 ///
131 /// - `codec`: Low-level codec owned by the engine.
132 /// - `input_len`: Number of input values the caller plans to encode.
133 ///
134 /// # Returns
135 ///
136 /// Returns a conservative upper bound for streaming output.
137 ///
138 /// # Errors
139 ///
140 /// Returns [`CapacityError::OutputLengthOverflow`] when the bound cannot
141 /// be represented as `usize`.
142 #[inline]
143 #[must_use = "capacity planning can fail on overflow"]
144 fn max_transcode_output_len(&self, _codec: &C, input_len: usize) -> Result<usize, CapacityError> {
145 input_len
146 .checked_mul(C::MAX_ENCODE_UNITS_PER_VALUE)
147 .ok_or(CapacityError::OutputLengthOverflow)
148 }
149
150 /// Returns an upper bound for units emitted by finishing hook-owned state.
151 ///
152 /// `finish` never receives more input values. Implementations must report
153 /// the maximum output that could be derived from hook-owned state in any
154 /// reachable transient stream state, not only what happens to remain when
155 /// this method is called.
156 ///
157 /// The default implementation returns `0`. Override it when
158 /// [`finish_hooks`](Self::finish_hooks) can write trailers, checksums,
159 /// delayed replacements, or any other hook-owned final output. Do not
160 /// include [`Codec::MAX_ENCODE_FINISH_UNITS`]; the engine adds the codec
161 /// finish bound separately.
162 ///
163 /// # Parameters
164 ///
165 /// - `codec`: Low-level codec owned by the engine.
166 ///
167 /// # Returns
168 ///
169 /// Returns the finite, transient-state-independent final-output upper
170 /// bound.
171 #[inline]
172 #[must_use]
173 fn max_finish_output_len(&self, _codec: &C) -> usize {
174 0
175 }
176
177 /// Handles one unencodable input value.
178 ///
179 /// # Parameters
180 ///
181 /// - `codec`: Low-level codec owned by the engine.
182 /// - `context`: Encode context for the input value that
183 /// [`Codec::can_encode_value`] rejected.
184 ///
185 /// # Returns
186 ///
187 /// Returns the action selected by this hook policy.
188 ///
189 /// Replacement actions must contain a value that the same codec can encode.
190 /// The engine treats unencodable replacements as hook contract violations
191 /// and panics.
192 ///
193 /// # Errors
194 ///
195 /// Returns [`crate::TranscodeEncodeError`] when the policy rejects the
196 /// value with a codec-domain error.
197 fn handle_unencodable_encode(
198 &mut self,
199 codec: &mut C,
200 context: &EncodeContext<'_, C::Value>,
201 ) -> Result<EncodeUnencodableAction<C::Value>, TranscodeEncodeErrorOf<C>>;
202
203 /// Runs hook-owned cleanup as part of stream reset.
204 ///
205 /// Called before [`Codec::encode_reset`] writes
206 /// its own reset output. Stateless hooks may use the default no-op.
207 ///
208 /// # Parameters
209 ///
210 /// - `codec`: Low-level codec owned by the engine.
211 #[inline]
212 fn reset_hooks(&mut self, _codec: &mut C) {}
213
214 /// Finishes hook-owned state and writes any retained output units.
215 ///
216 /// The default implementation is a no-op for stateless encode hooks.
217 /// Stateful hooks may emit final units such as reset sequences, checksums,
218 /// or trailers. The caller must provide at least
219 /// [`TranscodeEncodeHooks::max_finish_output_len`] writable units from
220 /// `output_index`. Implementations must not write beyond that declared
221 /// final-output bound.
222 ///
223 /// Called after [`Codec::encode_finish`] has
224 /// written its own finish output.
225 ///
226 /// # Parameters
227 ///
228 /// - `codec`: Low-level codec owned by the engine.
229 /// - `output`: Output unit slice visible to the hook.
230 /// - `output_index`: Absolute output unit index where writing starts.
231 ///
232 /// # Returns
233 ///
234 /// Returns the number of units written by finalization. This count must not
235 /// exceed [`TranscodeEncodeHooks::max_finish_output_len`].
236 ///
237 /// # Errors
238 ///
239 /// Returns a transcode encode error when hook-owned state cannot be
240 /// finalized.
241 #[inline]
242 fn finish_hooks(
243 &mut self,
244 _codec: &mut C,
245 _output: &mut [C::Unit],
246 _output_index: usize,
247 ) -> Result<usize, TranscodeEncodeErrorOf<C>> {
248 Ok(0)
249 }
250}