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.
96///
97/// # Examples
98///
99/// A minimal identity codec exposes its bounds and decodes one byte:
100///
101/// ```
102/// use core::convert::Infallible;
103/// use core::num::NonZeroUsize;
104///
105/// use qubit_codec::Codec;
106/// use qubit_codec::DecodeFailure;
107///
108/// struct Identity;
109/// impl Identity {
110/// fn new() -> Self { Self }
111/// }
112/// impl Codec for Identity {
113/// type Value = u8;
114/// type Unit = u8;
115/// type DecodeError = Infallible;
116/// type EncodeError = Infallible;
117/// const MIN_UNITS_PER_VALUE: usize = 1;
118/// const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
119/// const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
120///
121/// unsafe fn decode(&mut self, input: &[u8], index: usize)
122/// -> Result<(u8, NonZeroUsize), DecodeFailure<Infallible>> {
123/// Ok((input[index], NonZeroUsize::MIN))
124/// }
125///
126/// unsafe fn encode(&mut self, value: &u8, output: &mut [u8], index: usize)
127/// -> Result<usize, Infallible> {
128/// output[index] = *value;
129/// Ok(1)
130/// }
131/// }
132///
133/// let mut codec = Identity::new();
134/// assert_eq!(codec.encode_len(&42), 1);
135/// // SAFETY: the input contains the one readable unit required by Identity.
136/// let (value, consumed) = unsafe { codec.decode(&[42], 0) }.unwrap();
137/// assert_eq!((value, consumed.get()), (42, 1));
138/// ```
139pub trait Codec {
140 /// The type of logical values decoded from or encoded into the buffer.
141 type Value;
142
143 /// The type of buffer units used by the encoded representation.
144 type Unit;
145
146 /// The type of errors reported when decoding malformed units.
147 type DecodeError;
148
149 /// The type of errors reported when encoding an unsupported value.
150 type EncodeError;
151
152 /// The minimum possible non-zero readable unit count for one decoded value.
153 ///
154 /// This is a lower bound used by checked callers for planning and fast
155 /// impossibility checks. If a streaming decoder has fewer than this many
156 /// readable units, no complete value can be present at the current
157 /// position. It is also the denominator used by default decode hooks when
158 /// estimating the maximum number of values that can be produced from an
159 /// input unit count.
160 const MIN_UNITS_PER_VALUE: usize;
161
162 /// The maximum unit count emitted when encoding one value.
163 ///
164 /// This is a value-independent upper bound for the main encode phase. When
165 /// no concrete value is available, reserving this many writable units is
166 /// sufficient for any encodable value, without first calling
167 /// [`encode_len`](Self::encode_len). For a known value, callers may reserve
168 /// only the exact length returned by `encode_len` instead. This bound does
169 /// not include output produced by encode reset or finish phases.
170 ///
171 /// This is also the multiplier used by default encode hooks when estimating
172 /// the maximum number of output units needed for an input value count.
173 ///
174 /// The bound may be zero for a codec that buffers every accepted value and
175 /// emits retained output only during a later lifecycle phase.
176 const MAX_ENCODE_UNITS_PER_VALUE: usize;
177
178 /// The maximum non-zero unit count consumed to decode one value.
179 ///
180 /// This is a value-independent upper bound for one complete encoded value
181 /// or codec quantum on the decode side. Successful decode consumption and
182 /// the `required_total` carried by [`DecodeFailure::Incomplete`] must not
183 /// exceed this bound.
184 const MAX_DECODE_UNITS_PER_VALUE: usize;
185
186 /// The maximum unit count emitted when resetting encode state.
187 ///
188 /// This bound covers only output written by
189 /// [`encode_reset`](Self::encode_reset). It does not include hook-owned
190 /// reset output or any ordinary encoded input values. It must cover every
191 /// reachable pre-reset encode state. Stateless codecs should use the
192 /// default `0`.
193 const MAX_ENCODE_RESET_UNITS: usize = 0;
194
195 /// The maximum unit count emitted when finishing encode state at EOF.
196 ///
197 /// This bound covers only output written by
198 /// [`encode_finish`](Self::encode_finish). It does not include hook-owned
199 /// finish output and must cover every reachable encode state, even when the
200 /// current stream has no pending finish output. Stateless codecs should use
201 /// the default `0`. Codecs that emit a stream trailer (padding, checksum,
202 /// or end-of-stream marker) should override this with the exact maximum
203 /// unit count.
204 const MAX_ENCODE_FINISH_UNITS: usize = 0;
205
206 /// The maximum value count emitted when resetting decode state.
207 ///
208 /// This bound covers only values written by
209 /// [`decode_reset`](Self::decode_reset). It does not include hook-owned
210 /// reset output or values decoded from source units. It must cover every
211 /// reachable pre-reset decode state. Stateless codecs should use the
212 /// default `0`. Codecs that emit a stream-start sentinel or BOM on reset
213 /// should override this.
214 const MAX_DECODE_RESET_VALUES: usize = 0;
215
216 /// The maximum value count emitted when finishing decode state.
217 ///
218 /// This bound covers only values written by
219 /// [`decode_finish`](Self::decode_finish). It does not include hook-owned
220 /// finish output and must cover every reachable decode state, even when the
221 /// current stream has no pending finish output. Stateless codecs should use
222 /// the default `0`.
223 const MAX_DECODE_FINISH_VALUES: usize = 0;
224
225 /// Returns whether `value` is in this codec's encodable value domain.
226 ///
227 /// The default implementation returns `true`, which is correct for codecs
228 /// whose [`Value`](Self::Value) type contains only values they can encode.
229 /// Codecs whose logical value type is broader than their representation
230 /// domain, such as an ASCII codec with `Value = char`, must override this
231 /// method.
232 ///
233 /// Checked encoder adapters call this method in the same codec state used
234 /// to query [`encode_len`](Self::encode_len) and enter the unsafe
235 /// [`encode`](Self::encode) method. Complete-lifecycle adapters do so after
236 /// [`encode_reset`](Self::encode_reset). Direct unsafe callers must uphold
237 /// the same ordering.
238 ///
239 /// # Parameters
240 ///
241 /// - `value`: Value whose encodability is queried.
242 ///
243 /// # Returns
244 ///
245 /// Returns `true` when `value` may be passed to
246 /// [`encode_len`](Self::encode_len) and [`encode`](Self::encode).
247 #[inline]
248 #[must_use]
249 fn can_encode_value(&self, _value: &Self::Value) -> bool {
250 true
251 }
252
253 /// Returns the exact unit count this codec will write when encoding
254 /// `value`.
255 ///
256 /// The default implementation returns
257 /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE). This
258 /// default is correct only when every successful main encode writes exactly
259 /// that many units in the relevant codec state, as fixed-width codecs
260 /// normally do.
261 ///
262 /// Variable-width, buffering, or otherwise state-dependent codecs must
263 /// override this method to report the true encoded length for encodable
264 /// `value`s. The return value is never an estimate or an "unknown" marker:
265 /// it must equal the unit count [`encode`](Self::encode) subsequently
266 /// writes for the same `value` under the same codec state. It must also
267 /// never exceed
268 /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE).
269 /// Callers that do not yet have a concrete value should use
270 /// `MAX_ENCODE_UNITS_PER_VALUE` directly instead of calling this method.
271 ///
272 /// Default codec-backed encoders use this exact value for per-value output
273 /// capacity. The contract requires callers to use this method only when
274 /// [`can_encode_value`](Self::can_encode_value) returned `true` for the
275 /// same `value`.
276 ///
277 /// # Parameters
278 ///
279 /// - `value`: Value whose encoded length is queried.
280 ///
281 /// # Returns
282 ///
283 /// Returns the unit count [`encode`](Self::encode) will write for an
284 /// encodable `value`.
285 ///
286 /// A return value of `0` is valid for stateful encoders that accept a
287 /// value into internal state without immediately emitting units. Examples
288 /// include codecs that aggregate values into fixed-size quanta, shift-state
289 /// encodings, or framing layers that defer output until enough values have
290 /// been seen or EOF is finalized. Stateless and directly value-to-unit
291 /// codecs should continue returning a positive length.
292 #[inline]
293 #[must_use]
294 fn encode_len(&self, _value: &Self::Value) -> usize {
295 Self::MAX_ENCODE_UNITS_PER_VALUE
296 }
297
298 /// Emits stream-start output and resets encode-side state.
299 ///
300 /// # Parameters
301 ///
302 /// - `output`: Destination unit buffer.
303 /// - `output_index`: Start index in `output`.
304 ///
305 /// # Returns
306 ///
307 /// Returns the number of reset units written.
308 ///
309 /// # Errors
310 ///
311 /// Returns `Self::EncodeError` when reset output cannot be emitted.
312 /// Implementations must leave encode state unchanged when returning an
313 /// error.
314 ///
315 /// # Safety
316 ///
317 /// The caller must guarantee that the implementation can write up to
318 /// [`MAX_ENCODE_RESET_UNITS`](Self::MAX_ENCODE_RESET_UNITS) units starting
319 /// at `output_index`.
320 #[inline]
321 unsafe fn encode_reset(
322 &mut self,
323 _output: &mut [Self::Unit],
324 _output_index: usize,
325 ) -> Result<usize, Self::EncodeError> {
326 Ok(0)
327 }
328
329 /// Encodes one borrowed value into `output` starting at `output_index`.
330 ///
331 /// # Parameters
332 ///
333 /// - `value`: Value to encode.
334 /// - `output`: Destination unit buffer.
335 /// - `output_index`: Start index in `output`.
336 ///
337 /// # Returns
338 ///
339 /// Returns the number of written units.
340 ///
341 /// A successful encode may return `0` when the codec accepted `value` into
342 /// internal encode-side state but intentionally deferred output. This is
343 /// the normal shape for accumulative encoders such as base64-byte
344 /// aggregators, shift-state encodings, or frame builders. In that case
345 /// [`encode_len`](Self::encode_len) for the same `value` and state must
346 /// also return `0`, and the retained output must be emitted by a later
347 /// successful [`encode`](Self::encode),
348 /// [`encode_finish`](Self::encode_finish), or codec-specific facade.
349 ///
350 /// # Errors
351 ///
352 /// Returns `Self::EncodeError` for encode-side state or representation
353 /// failures other than a value being outside the codec's encodable domain.
354 /// Checked callers reject values for which
355 /// [`can_encode_value`](Self::can_encode_value) returns `false` before
356 /// entering this unsafe method. Implementations must leave their internal
357 /// state consistent when returning an error.
358 ///
359 /// # Safety
360 ///
361 /// The caller must guarantee that
362 /// [`can_encode_value`](Self::can_encode_value) returned `true` for
363 /// `value`. Starting at `output_index`, the caller must also provide either
364 /// at least
365 /// [`MAX_ENCODE_UNITS_PER_VALUE`](Self::MAX_ENCODE_UNITS_PER_VALUE)
366 /// writable
367 /// units, which is sufficient for every encodable value, or at least the
368 /// exact [`encode_len`](Self::encode_len) for the same `value` and codec
369 /// state. On success, implementations must return that exact written unit
370 /// count, including `0` for deliberate buffering, and the count must be no
371 /// larger than `MAX_ENCODE_UNITS_PER_VALUE`. Implementations must not write
372 /// beyond the exact `encode_len` capacity on either the success or error
373 /// path.
374 unsafe fn encode(
375 &mut self,
376 value: &Self::Value,
377 output: &mut [Self::Unit],
378 output_index: usize,
379 ) -> Result<usize, Self::EncodeError>;
380
381 /// Emits EOF trailer output and finishes encode-side state.
382 ///
383 /// This is the encode-side counterpart of
384 /// [`decode_finish`](Self::decode_finish). Codecs that append stream
385 /// trailers (padding, checksums, end-of-stream markers) emit them here.
386 /// Stateless codecs use the default no-op.
387 ///
388 /// # Parameters
389 ///
390 /// - `output`: Destination unit buffer.
391 /// - `output_index`: Start index in `output`.
392 ///
393 /// # Returns
394 ///
395 /// Returns the number of finish units written.
396 ///
397 /// # Errors
398 ///
399 /// Returns `Self::EncodeError` when finish output cannot be emitted.
400 /// Implementations must leave their internal state consistent when
401 /// returning an error.
402 ///
403 /// # Safety
404 ///
405 /// The caller must guarantee that the implementation can write up to
406 /// [`MAX_ENCODE_FINISH_UNITS`](Self::MAX_ENCODE_FINISH_UNITS) units
407 /// starting at `output_index`.
408 #[inline]
409 unsafe fn encode_finish(
410 &mut self,
411 _output: &mut [Self::Unit],
412 _output_index: usize,
413 ) -> Result<usize, Self::EncodeError> {
414 Ok(0)
415 }
416
417 /// Emits stream-start values and resets decode-side state.
418 ///
419 /// This is the decode-side counterpart of
420 /// [`encode_reset`](Self::encode_reset). Codecs that emit a
421 /// stream-start marker or BOM before decoding a new stream emit them
422 /// here. Stateless codecs use the default no-op.
423 ///
424 /// # Parameters
425 ///
426 /// - `output`: Destination value buffer.
427 /// - `output_index`: Start index in `output`.
428 ///
429 /// # Returns
430 ///
431 /// Returns the number of reset values written.
432 ///
433 /// # Errors
434 ///
435 /// Returns `Self::DecodeError` when reset output cannot be emitted.
436 /// Implementations must leave their internal state consistent when
437 /// returning an error.
438 ///
439 /// # Safety
440 ///
441 /// The caller must guarantee that the implementation can write up to
442 /// [`MAX_DECODE_RESET_VALUES`](Self::MAX_DECODE_RESET_VALUES) values
443 /// starting at `output_index`.
444 #[inline]
445 unsafe fn decode_reset(
446 &mut self,
447 _output: &mut [Self::Value],
448 _output_index: usize,
449 ) -> Result<usize, Self::DecodeError> {
450 Ok(0)
451 }
452
453 /// Decodes one value from `input` starting at `input_index`.
454 ///
455 /// # Parameters
456 ///
457 /// - `input`: Source unit buffer.
458 /// - `input_index`: Start index in `input`.
459 ///
460 /// # Returns
461 ///
462 /// Returns the decoded value and the non-zero number of consumed units.
463 ///
464 /// # Errors
465 ///
466 /// Returns [`DecodeFailure::Incomplete`] when the visible input is a
467 /// valid prefix but more units are needed to decide or complete a value.
468 /// This reports a streaming boundary, not a final EOF condition; the
469 /// caller or higher-level adapter decides what an incomplete tail means
470 /// when the upstream source is closed. Codec-specific context may be
471 /// retained in the failure's optional `source` field.
472 /// Returns [`DecodeFailure::Invalid`] when the units are malformed,
473 /// non-canonical, unmappable, or otherwise invalid for this codec and the
474 /// span is known or unknown. Unknown span is represented as
475 /// [`DecodeFailure::Invalid`] with an unknown consumed-unit hint.
476 /// Implementations must leave their internal state consistent when
477 /// returning an error.
478 ///
479 /// # Safety
480 ///
481 /// The caller must guarantee that `input_index` is a valid boundary in
482 /// `input` and that at least
483 /// [`MIN_UNITS_PER_VALUE`](Self::MIN_UNITS_PER_VALUE)
484 /// units are readable from `input_index`. Implementations must not read
485 /// beyond the currently available units under that precondition. They
486 /// may return [`DecodeFailure::Incomplete`] when those units are a
487 /// valid but incomplete prefix.
488 ///
489 /// On success, implementations must return a consumed unit count no larger
490 /// than either the available input or
491 /// [`MAX_DECODE_UNITS_PER_VALUE`](Self::MAX_DECODE_UNITS_PER_VALUE). An
492 /// incomplete result's `required_total` must also not exceed that maximum.
493 /// The return type guarantees that successful decoding always consumes at
494 /// least one unit. Implementations should use `debug_assert!` to state
495 /// these unchecked entry-point assumptions.
496 unsafe fn decode(
497 &mut self,
498 input: &[Self::Unit],
499 input_index: usize,
500 ) -> Result<(Self::Value, NonZeroUsize), DecodeFailure<Self::DecodeError>>;
501
502 /// Decodes one value after the caller has established end of input.
503 ///
504 /// This method has the same safety and state guarantees as
505 /// [`decode`](Self::decode), but may resolve an otherwise incomplete
506 /// trailing prefix using EOF-aware format rules. The default preserves the
507 /// open-stream behavior by delegating to [`decode`](Self::decode).
508 ///
509 /// # Parameters
510 ///
511 /// - `input`: Final source unit buffer; no more units will arrive.
512 /// - `input_index`: Start index of the value in `input`.
513 ///
514 /// # Returns
515 ///
516 /// Returns the decoded value and the non-zero number of consumed units.
517 ///
518 /// # Errors
519 ///
520 /// Returns [`DecodeFailure::Incomplete`] for an unresolved final prefix,
521 /// or [`DecodeFailure::Invalid`] for malformed input, as in
522 /// [`decode`](Self::decode). An override may resolve a prefix at EOF.
523 ///
524 /// # Safety
525 ///
526 /// The caller must satisfy the same input-index and minimum-readable-unit
527 /// preconditions as [`decode`](Self::decode). Implementations must not
528 /// read beyond the currently available units.
529 #[inline]
530 unsafe fn decode_eof(
531 &mut self,
532 input: &[Self::Unit],
533 input_index: usize,
534 ) -> Result<(Self::Value, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
535 // SAFETY: `decode_eof` has the same preconditions as `decode`.
536 unsafe { self.decode(input, input_index) }
537 }
538
539 /// Finishes decode-side EOF state into `output`.
540 ///
541 /// `decode_finish` receives no source input. Callers must have already
542 /// handled any tail reported by [`DecodeFailure::Incomplete`] before
543 /// finishing decode state. Implementations may emit retained values or
544 /// validate internal EOF state, but they must not depend on re-reading the
545 /// incomplete source tail.
546 ///
547 /// # Parameters
548 ///
549 /// - `output`: Destination value buffer.
550 /// - `output_index`: Start index in `output`.
551 ///
552 /// # Returns
553 ///
554 /// Returns the number of finished values written.
555 ///
556 /// # Errors
557 ///
558 /// Returns `Self::DecodeError` when retained decode state is invalid at
559 /// EOF. Implementations must leave their internal state consistent when
560 /// returning an error.
561 ///
562 /// # Safety
563 ///
564 /// The caller must guarantee that the implementation can write up to
565 /// [`MAX_DECODE_FINISH_VALUES`](Self::MAX_DECODE_FINISH_VALUES) values
566 /// starting at `output_index`.
567 #[inline]
568 unsafe fn decode_finish(
569 &mut self,
570 _output: &mut [Self::Value],
571 _output_index: usize,
572 ) -> Result<usize, Self::DecodeError> {
573 Ok(0)
574 }
575}
576
577/// Compile-time asserts the public unit-bound invariants required by [`Codec`].
578///
579/// # Type Parameters
580///
581/// - `C`: Codec implementation to validate.
582///
583/// # Returns
584///
585/// Returns unit `()`.
586///
587/// # Panics
588///
589/// Panics at compile time when either decode width bound is zero or when
590/// [`Codec::MIN_UNITS_PER_VALUE`] is greater than
591/// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], because these invariants must hold
592/// for any well-formed [`Codec`] implementation and violating them is always a
593/// bug.
594#[inline]
595pub(crate) fn assert_unit_bounds<C>()
596where
597 C: Codec,
598{
599 const {
600 assert!(
601 C::MIN_UNITS_PER_VALUE > 0,
602 "Codec::MIN_UNITS_PER_VALUE must be non-zero",
603 );
604 assert!(
605 C::MAX_DECODE_UNITS_PER_VALUE > 0,
606 "Codec::MAX_DECODE_UNITS_PER_VALUE must be non-zero",
607 );
608 assert!(
609 C::MIN_UNITS_PER_VALUE <= C::MAX_DECODE_UNITS_PER_VALUE,
610 "Codec::MIN_UNITS_PER_VALUE must not exceed Codec::MAX_DECODE_UNITS_PER_VALUE",
611 );
612 }
613}