qubit_codec_text/encode/charset_encode_probe.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// =============================================================================
8use crate::{
9 CharsetCodec,
10 CharsetEncodeResult,
11};
12
13/// Encoding-size probe used by [`crate::CharsetEncoder`].
14///
15/// Encoders use this trait to validate mappability and compute the exact output
16/// unit count before calling unsafe [`qubit_codec::Codec::encode_unchecked`].
17///
18/// # Implementor Contract
19///
20/// For the same codec state, input character, and output index, a successful
21/// [`Self::encode_len`] call must return exactly the number of units that
22/// [`qubit_codec::Codec::encode_unchecked`] will write when the caller supplies
23/// sufficient output capacity. Both methods must also agree on charset
24/// mappability: a character accepted by `encode_len` must not later be reported
25/// as unmappable by `encode_unchecked`, and a character rejected as unmappable
26/// by `encode_len` must not be encoded by `encode_unchecked`.
27pub trait CharsetEncodeProbe: CharsetCodec {
28 /// Computes the number of units needed to encode one character.
29 ///
30 /// # Parameters
31 ///
32 /// - `ch`: Unicode scalar value to encode.
33 /// - `index`: Input character index used for error context.
34 ///
35 /// # Returns
36 ///
37 /// Returns the exact number of output units required for `ch`.
38 ///
39 /// # Errors
40 ///
41 /// Returns [`crate::CharsetEncodeError`] when `ch` cannot be represented by
42 /// this charset.
43 fn encode_len(&self, ch: char, index: usize) -> CharsetEncodeResult<usize>;
44}