Skip to main content

qubit_codec/codec/
codec.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//! Low-level value codec trait.
9
10use core::num::NonZeroUsize;
11
12use super::decode_failure::DecodeFailure;
13
14/// Encodes and decodes one value or codec quantum against a unit buffer.
15///
16/// `Codec` is the lowest-level abstraction in the codec stack. It is intended
17/// for hot paths that have already validated buffer capacity and want to avoid
18/// constructing subslices for every value. Higher-level transcoders and
19/// convenience APIs are responsible for checked buffer management and owned
20/// output allocation.
21///
22/// `MIN_UNITS_PER_VALUE` and `MAX_DECODE_UNITS_PER_VALUE` describe the readable
23/// representation-width bounds for one decoded value. If fewer than the
24/// minimum units are available, no complete value can exist, so a streaming
25/// caller can request more input or report an incomplete EOF tail. The minimum
26/// is also the smallest safety precondition checked callers must satisfy before
27/// entering [`decode`](Self::decode). The decode maximum bounds successful
28/// consumption and incomplete-input requirements for one value.
29///
30/// `MAX_ENCODE_UNITS_PER_VALUE` is the independent value-agnostic upper bound
31/// for main-phase encode output. Reserving that many units makes encoding safe
32/// for every encodable value. Once a value and encode state are known, callers
33/// may instead reserve the exact [`encode_len`](Self::encode_len), which must
34/// not exceed the encode maximum. Complete-lifecycle adapters that still need
35/// to run [`encode_reset`](Self::encode_reset) must reserve the maximum first
36/// because reset may change the exact width.
37///
38/// A codec may keep decode-side and encode-side stream state. That state is an
39/// implementation detail owned by the codec. Callers do not snapshot or restore
40/// it; implementations must keep their own state internally consistent across
41/// every public operation. A failed decode attempt must not advance decode
42/// state, so callers can retry the same input after refilling their buffer or
43/// applying an invalid-input policy.
44///
45/// Decode operations see only the currently supplied input slice and codec
46/// state. [`decode`](Self::decode) treats that slice as an open stream segment;
47/// [`decode_eof`](Self::decode_eof) receives the same preconditions after the
48/// caller has established that no more units will arrive. Returning
49/// [`DecodeFailure::Incomplete`] from `decode` requests more input for the
50/// current value; it is not itself an EOF error. Codecs that need EOF-aware
51/// maximal-munch parsing or reinterpretation of a trailing prefix can override
52/// `decode_eof` without changing their streaming behavior.
53/// An incomplete failure may also retain codec-specific context through
54/// [`DecodeFailure::incomplete_with_source`]; stream drivers may ignore that
55/// context while retrying and use it for detailed EOF diagnostics.
56///
57/// # Associated Types
58///
59/// - `Value`: Logical value decoded from or encoded into the buffer. This may
60///   be a scalar such as `u8`, `u16`, `u64`, a `char`, a fixed quantum such as
61///   `[u8; 3]`, or an owned value such as `String`/`Vec<u8>`. Adapters that
62///   need scratch initialization add their own bounds at the use site.
63/// - `Unit`: Buffer unit used by the encoded representation. Implementations
64///   are typically scalar storage units such as `u8`, `u16`, or `char`.
65///   Adapters that allocate owned output add their own initialization bounds at
66///   the use site.
67///
68/// Implementors must uphold the safety contract documented by
69/// [`decode`](Self::decode), [`encode`](Self::encode),
70/// [`encode_reset`](Self::encode_reset), and
71/// [`decode_finish`](Self::decode_finish). Unchecked implementations must not
72/// read or write outside the caller-provided ranges. Implementations should use
73/// `debug_assert!` to state the expected buffer bounds at the unchecked entry
74/// point.
75///
76/// Implementations must also guarantee that
77/// [`MIN_UNITS_PER_VALUE`](Self::MIN_UNITS_PER_VALUE) is non-zero and no larger
78/// than [`MAX_DECODE_UNITS_PER_VALUE`](Self::MAX_DECODE_UNITS_PER_VALUE), which
79/// must also be non-zero. `MAX_ENCODE_UNITS_PER_VALUE` may be zero for a codec
80/// that always buffers each accepted value instead of immediately emitting
81/// units. Checked adapters enforce the decode-bound invariants with
82/// compile-time assertions before using codec-provided bounds.
83///
84/// # Why the low-level methods are unchecked
85///
86/// The `unsafe` entry points are intentional: checked adapters validate the
87/// index and capacity preconditions once, then call [`encode`](Self::encode)
88/// and [`decode`](Self::decode) without rebuilding subslices or repeating
89/// bounds checks for every value. The `safe_vs_unchecked` benchmark in
90/// `benches/transcode.rs` compares the same 64 KiB copy loop in release mode.
91/// Its result is workload- and toolchain-specific, so callers should use
92/// checked adapters unless they can establish the documented preconditions at
93/// a trusted boundary. Measure representative codec workloads before choosing
94/// an unchecked entry point. Codec implementations should keep the unchecked
95/// methods small and use `debug_assert!` for those assumptions.
96pub trait Codec {
97    /// The type of logical values decoded from or encoded into the buffer.
98    type Value;
99
100    /// The type of buffer units used by the encoded representation.
101    type Unit;
102
103    /// The type of errors reported when decoding malformed units.
104    type DecodeError;
105
106    /// The type of errors reported when encoding an unsupported value.
107    type EncodeError;
108
109    /// The minimum possible non-zero readable unit count for one decoded value.
110    ///
111    /// This is a lower bound used by checked callers for planning and fast
112    /// impossibility checks. If a streaming decoder has fewer than this many
113    /// readable units, no complete value can be present at the current
114    /// position. It is also the denominator used by default decode hooks when
115    /// estimating the maximum number of values that can be produced from an
116    /// input unit count.
117    const MIN_UNITS_PER_VALUE: usize;
118
119    /// The maximum unit count emitted when encoding one value.
120    ///
121    /// This is a value-independent upper bound for the main encode phase. When
122    /// no concrete value is available, reserving this many writable units is
123    /// sufficient for any encodable value, without first calling
124    /// [`encode_len`](Self::encode_len). For a known value, callers may reserve
125    /// only the exact length returned by `encode_len` instead. This bound does
126    /// not include output produced by encode reset or finish phases.
127    ///
128    /// This is also the multiplier used by default encode hooks when estimating
129    /// the maximum number of output units needed for an input value count.
130    ///
131    /// The bound may be zero for a codec that buffers every accepted value and
132    /// emits retained output only during a later lifecycle phase.
133    const MAX_ENCODE_UNITS_PER_VALUE: usize;
134
135    /// The maximum non-zero unit count consumed to decode one value.
136    ///
137    /// This is a value-independent upper bound for one complete encoded value
138    /// or codec quantum on the decode side. Successful decode consumption and
139    /// the `required_total` carried by [`DecodeFailure::Incomplete`] must not
140    /// exceed this bound.
141    const MAX_DECODE_UNITS_PER_VALUE: usize;
142
143    /// The maximum unit count emitted when resetting encode state.
144    ///
145    /// This bound covers only output written by
146    /// [`encode_reset`](Self::encode_reset). It does not include hook-owned
147    /// reset output or any ordinary encoded input values. It must cover every
148    /// reachable pre-reset encode state. Stateless codecs should use the
149    /// default `0`.
150    const MAX_ENCODE_RESET_UNITS: usize = 0;
151
152    /// The maximum unit count emitted when finishing encode state at EOF.
153    ///
154    /// This bound covers only output written by
155    /// [`encode_finish`](Self::encode_finish). It does not include hook-owned
156    /// finish output and must cover every reachable encode state, even when the
157    /// current stream has no pending finish output. Stateless codecs should use
158    /// the default `0`. Codecs that emit a stream trailer (padding, checksum,
159    /// or end-of-stream marker) should override this with the exact maximum
160    /// unit count.
161    const MAX_ENCODE_FINISH_UNITS: usize = 0;
162
163    /// The maximum value count emitted when resetting decode state.
164    ///
165    /// This bound covers only values written by
166    /// [`decode_reset`](Self::decode_reset). It does not include hook-owned
167    /// reset output or values decoded from source units. It must cover every
168    /// reachable pre-reset decode state. Stateless codecs should use the
169    /// default `0`. Codecs that emit a stream-start sentinel or BOM on reset
170    /// should override this.
171    const MAX_DECODE_RESET_VALUES: usize = 0;
172
173    /// The maximum value count emitted when finishing decode state.
174    ///
175    /// This bound covers only values written by
176    /// [`decode_finish`](Self::decode_finish). It does not include hook-owned
177    /// finish output and must cover every reachable decode state, even when the
178    /// current stream has no pending finish output. Stateless codecs should use
179    /// the default `0`.
180    const MAX_DECODE_FINISH_VALUES: usize = 0;
181
182    /// Returns whether `value` is in this codec's encodable value domain.
183    ///
184    /// The default implementation returns `true`, which is correct for codecs
185    /// whose [`Value`](Self::Value) type contains only values they can encode.
186    /// Codecs whose logical value type is broader than their representation
187    /// domain, such as an ASCII codec with `Value = char`, must override this
188    /// method.
189    ///
190    /// Checked encoder adapters call this method in the same codec state used
191    /// to query [`encode_len`](Self::encode_len) and enter the unsafe
192    /// [`encode`](Self::encode) method. Complete-lifecycle adapters do so after
193    /// [`encode_reset`](Self::encode_reset). Direct unsafe callers must uphold
194    /// the same ordering.
195    ///
196    /// # Parameters
197    ///
198    /// - `value`: Value whose encodability is queried.
199    ///
200    /// # Returns
201    ///
202    /// Returns `true` when `value` may be passed to
203    /// [`encode_len`](Self::encode_len) and [`encode`](Self::encode).
204    #[inline(always)]
205    #[must_use]
206    fn can_encode_value(&self, _value: &Self::Value) -> bool {
207        true
208    }
209
210    /// Returns the exact unit count this codec will write when encoding
211    /// `value`.
212    ///
213    /// The default implementation returns
214    /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE). This
215    /// default is correct only when every successful main encode writes exactly
216    /// that many units in the relevant codec state, as fixed-width codecs
217    /// normally do.
218    ///
219    /// Variable-width, buffering, or otherwise state-dependent codecs must
220    /// override this method to report the true encoded length for encodable
221    /// `value`s. The return value is never an estimate or an "unknown" marker:
222    /// it must equal the unit count [`encode`](Self::encode) subsequently
223    /// writes for the same `value` under the same codec state. It must also
224    /// never exceed
225    /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE).
226    /// Callers that do not yet have a concrete value should use
227    /// `MAX_ENCODE_UNITS_PER_VALUE` directly instead of calling this method.
228    ///
229    /// Default codec-backed encoders use this exact value for per-value output
230    /// capacity. The contract requires callers to use this method only when
231    /// [`can_encode_value`](Self::can_encode_value) returned `true` for the
232    /// same `value`.
233    ///
234    /// # Parameters
235    ///
236    /// - `value`: Value whose encoded length is queried.
237    ///
238    /// # Returns
239    ///
240    /// Returns the unit count [`encode`](Self::encode) will write for an
241    /// encodable `value`.
242    ///
243    /// A return value of `0` is valid for stateful encoders that accept a
244    /// value into internal state without immediately emitting units. Examples
245    /// include codecs that aggregate values into fixed-size quanta, shift-state
246    /// encodings, or framing layers that defer output until enough values have
247    /// been seen or EOF is finalized. Stateless and directly value-to-unit
248    /// codecs should continue returning a positive length.
249    #[inline(always)]
250    #[must_use]
251    fn encode_len(&self, _value: &Self::Value) -> usize {
252        Self::MAX_ENCODE_UNITS_PER_VALUE
253    }
254
255    /// Emits stream-start output and resets encode-side state.
256    ///
257    /// # Parameters
258    ///
259    /// - `output`: Destination unit buffer.
260    /// - `output_index`: Start index in `output`.
261    ///
262    /// # Returns
263    ///
264    /// Returns the number of reset units written.
265    ///
266    /// # Errors
267    ///
268    /// Returns `Self::EncodeError` when reset output cannot be emitted.
269    /// Implementations must leave encode state unchanged when returning an
270    /// error.
271    ///
272    /// # Safety
273    ///
274    /// The caller must guarantee that the implementation can write up to
275    /// [`MAX_ENCODE_RESET_UNITS`](Self::MAX_ENCODE_RESET_UNITS) units starting
276    /// at `output_index`.
277    #[inline(always)]
278    #[must_use = "reset output and reset errors must be handled"]
279    unsafe fn encode_reset(
280        &mut self,
281        _output: &mut [Self::Unit],
282        _output_index: usize,
283    ) -> Result<usize, Self::EncodeError> {
284        Ok(0)
285    }
286
287    /// Encodes one borrowed value into `output` starting at `output_index`.
288    ///
289    /// # Parameters
290    ///
291    /// - `value`: Value to encode.
292    /// - `output`: Destination unit buffer.
293    /// - `output_index`: Start index in `output`.
294    ///
295    /// # Returns
296    ///
297    /// Returns the number of written units.
298    ///
299    /// A successful encode may return `0` when the codec accepted `value` into
300    /// internal encode-side state but intentionally deferred output. This is
301    /// the normal shape for accumulative encoders such as base64-byte
302    /// aggregators, shift-state encodings, or frame builders. In that case
303    /// [`encode_len`](Self::encode_len) for the same `value` and state must
304    /// also return `0`, and the retained output must be emitted by a later
305    /// successful [`encode`](Self::encode),
306    /// [`encode_finish`](Self::encode_finish), or codec-specific facade.
307    ///
308    /// # Errors
309    ///
310    /// Returns `Self::EncodeError` for encode-side state or representation
311    /// failures other than a value being outside the codec's encodable domain.
312    /// Checked callers reject values for which
313    /// [`can_encode_value`](Self::can_encode_value) returns `false` before
314    /// entering this unsafe method. Implementations must leave their internal
315    /// state consistent when returning an error.
316    ///
317    /// # Safety
318    ///
319    /// The caller must guarantee that
320    /// [`can_encode_value`](Self::can_encode_value) returned `true` for
321    /// `value`. Starting at `output_index`, the caller must also provide either
322    /// at least
323    /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE)
324    /// writable
325    /// units, which is sufficient for every encodable value, or at least the
326    /// exact [`encode_len`](Self::encode_len) for the same `value` and codec
327    /// state. On success, implementations must return that exact written unit
328    /// count, including `0` for deliberate buffering, and the count must be no
329    /// larger than `MAX_ENCODE_UNITS_PER_VALUE`. Implementations must not write
330    /// beyond the exact `encode_len` capacity on either the success or error
331    /// path.
332    #[must_use = "encoded length and encode errors must be handled"]
333    unsafe fn encode(
334        &mut self,
335        value: &Self::Value,
336        output: &mut [Self::Unit],
337        output_index: usize,
338    ) -> Result<usize, Self::EncodeError>;
339
340    /// Emits EOF trailer output and finishes encode-side state.
341    ///
342    /// This is the encode-side counterpart of
343    /// [`decode_finish`](Self::decode_finish). Codecs that append stream
344    /// trailers (padding, checksums, end-of-stream markers) emit them here.
345    /// Stateless codecs use the default no-op.
346    ///
347    /// # Parameters
348    ///
349    /// - `output`: Destination unit buffer.
350    /// - `output_index`: Start index in `output`.
351    ///
352    /// # Returns
353    ///
354    /// Returns the number of finish units written.
355    ///
356    /// # Errors
357    ///
358    /// Returns `Self::EncodeError` when finish output cannot be emitted.
359    /// Implementations must leave their internal state consistent when
360    /// returning an error.
361    ///
362    /// # Safety
363    ///
364    /// The caller must guarantee that the implementation can write up to
365    /// [`MAX_ENCODE_FINISH_UNITS`](Self::MAX_ENCODE_FINISH_UNITS) units
366    /// starting at `output_index`.
367    #[inline(always)]
368    #[must_use = "finish output and finish errors must be handled"]
369    unsafe fn encode_finish(
370        &mut self,
371        _output: &mut [Self::Unit],
372        _output_index: usize,
373    ) -> Result<usize, Self::EncodeError> {
374        Ok(0)
375    }
376
377    /// Emits stream-start values and resets decode-side state.
378    ///
379    /// This is the decode-side counterpart of
380    /// [`encode_reset`](Self::encode_reset). Codecs that emit a
381    /// stream-start marker or BOM before decoding a new stream emit them
382    /// here. Stateless codecs use the default no-op.
383    ///
384    /// # Parameters
385    ///
386    /// - `output`: Destination value buffer.
387    /// - `output_index`: Start index in `output`.
388    ///
389    /// # Returns
390    ///
391    /// Returns the number of reset values written.
392    ///
393    /// # Errors
394    ///
395    /// Returns `Self::DecodeError` when reset output cannot be emitted.
396    /// Implementations must leave their internal state consistent when
397    /// returning an error.
398    ///
399    /// # Safety
400    ///
401    /// The caller must guarantee that the implementation can write up to
402    /// [`MAX_DECODE_RESET_VALUES`](Self::MAX_DECODE_RESET_VALUES) values
403    /// starting at `output_index`.
404    #[inline(always)]
405    #[must_use = "reset output and reset errors must be handled"]
406    unsafe fn decode_reset(
407        &mut self,
408        _output: &mut [Self::Value],
409        _output_index: usize,
410    ) -> Result<usize, Self::DecodeError> {
411        Ok(0)
412    }
413
414    /// Decodes one value from `input` starting at `input_index`.
415    ///
416    /// # Parameters
417    ///
418    /// - `input`: Source unit buffer.
419    /// - `input_index`: Start index in `input`.
420    ///
421    /// # Returns
422    ///
423    /// Returns the decoded value and the non-zero number of consumed units.
424    ///
425    /// # Errors
426    ///
427    /// Returns [`DecodeFailure::Incomplete`] when the visible input is a
428    /// valid prefix but more units are needed to decide or complete a value.
429    /// This reports a streaming boundary, not a final EOF condition; the
430    /// caller or higher-level adapter decides what an incomplete tail means
431    /// when the upstream source is closed. Codec-specific context may be
432    /// retained in the failure's optional `source` field.
433    /// Returns [`DecodeFailure::Invalid`] when the units are malformed,
434    /// non-canonical, unmappable, or otherwise invalid for this codec and the
435    /// span is known or unknown. Unknown span is represented as
436    /// [`DecodeFailure::Invalid`] with an unknown consumed-unit hint.
437    /// Implementations must leave their internal state consistent when
438    /// returning an error.
439    ///
440    /// # Safety
441    ///
442    /// The caller must guarantee that `input_index` is a valid boundary in
443    /// `input` and that at least
444    /// [`MIN_UNITS_PER_VALUE`](Self::MIN_UNITS_PER_VALUE)
445    /// units are readable from `input_index`. Implementations must not read
446    /// beyond the currently available units under that precondition. They
447    /// may return [`DecodeFailure::Incomplete`] when those units are a
448    /// valid but incomplete prefix.
449    ///
450    /// On success, implementations must return a consumed unit count no larger
451    /// than either the available input or
452    /// [`MAX_DECODE_UNITS_PER_VALUE`](Self::MAX_DECODE_UNITS_PER_VALUE). An
453    /// incomplete result's `required_total` must also not exceed that maximum.
454    /// The return type guarantees that successful decoding always consumes at
455    /// least one unit. Implementations should use `debug_assert!` to state
456    /// these unchecked entry-point assumptions.
457    #[must_use = "decoded value, consumed length, and decode errors must be handled"]
458    unsafe fn decode(
459        &mut self,
460        input: &[Self::Unit],
461        input_index: usize,
462    ) -> Result<(Self::Value, NonZeroUsize), DecodeFailure<Self::DecodeError>>;
463
464    /// Decodes one value after the caller has established end of input.
465    ///
466    /// This method has the same safety and state guarantees as
467    /// [`decode`](Self::decode), but may resolve an otherwise incomplete
468    /// trailing prefix using EOF-aware format rules. The default preserves the
469    /// open-stream behavior by delegating to [`decode`](Self::decode).
470    ///
471    /// # Safety
472    ///
473    /// The caller must satisfy the same input-index and minimum-readable-unit
474    /// preconditions as [`decode`](Self::decode). Implementations must not
475    /// read beyond the currently available units.
476    #[inline(always)]
477    #[must_use = "decoded value, consumed length, and decode errors must be handled"]
478    unsafe fn decode_eof(
479        &mut self,
480        input: &[Self::Unit],
481        input_index: usize,
482    ) -> Result<(Self::Value, NonZeroUsize), DecodeFailure<Self::DecodeError>>
483    {
484        // SAFETY: `decode_eof` has the same preconditions as `decode`.
485        unsafe { self.decode(input, input_index) }
486    }
487
488    /// Finishes decode-side EOF state into `output`.
489    ///
490    /// `decode_finish` receives no source input. Callers must have already
491    /// handled any tail reported by [`DecodeFailure::Incomplete`] before
492    /// finishing decode state. Implementations may emit retained values or
493    /// validate internal EOF state, but they must not depend on re-reading the
494    /// incomplete source tail.
495    ///
496    /// # Parameters
497    ///
498    /// - `output`: Destination value buffer.
499    /// - `output_index`: Start index in `output`.
500    ///
501    /// # Returns
502    ///
503    /// Returns the number of finished values written.
504    ///
505    /// # Errors
506    ///
507    /// Returns `Self::DecodeError` when retained decode state is invalid at
508    /// EOF. Implementations must leave their internal state consistent when
509    /// returning an error.
510    ///
511    /// # Safety
512    ///
513    /// The caller must guarantee that the implementation can write up to
514    /// [`MAX_DECODE_FINISH_VALUES`](Self::MAX_DECODE_FINISH_VALUES) values
515    /// starting at `output_index`.
516    #[inline(always)]
517    #[must_use = "finish output length and finish errors must be handled"]
518    unsafe fn decode_finish(
519        &mut self,
520        _output: &mut [Self::Value],
521        _output_index: usize,
522    ) -> Result<usize, Self::DecodeError> {
523        Ok(0)
524    }
525}
526
527/// Compile-time asserts the public unit-bound invariants required by [`Codec`].
528///
529/// # Type Parameters
530///
531/// - `C`: Codec implementation to validate.
532///
533/// # Returns
534///
535/// Returns unit `()`.
536///
537/// # Panics
538///
539/// Panics at compile time when either decode width bound is zero or when
540/// [`Codec::MIN_UNITS_PER_VALUE`] is greater than
541/// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], because these invariants must hold
542/// for any well-formed [`Codec`] implementation and violating them is always a
543/// bug.
544#[inline(always)]
545pub(crate) fn assert_unit_bounds<C>()
546where
547    C: Codec,
548{
549    const {
550        assert!(
551            C::MIN_UNITS_PER_VALUE > 0,
552            "Codec::MIN_UNITS_PER_VALUE must be non-zero",
553        );
554        assert!(
555            C::MAX_DECODE_UNITS_PER_VALUE > 0,
556            "Codec::MAX_DECODE_UNITS_PER_VALUE must be non-zero",
557        );
558        assert!(
559            C::MIN_UNITS_PER_VALUE <= C::MAX_DECODE_UNITS_PER_VALUE,
560            "Codec::MIN_UNITS_PER_VALUE must not exceed Codec::MAX_DECODE_UNITS_PER_VALUE",
561        );
562    }
563}