Skip to main content

qubit_codec_text/encode/
charset_encode_policy.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::UnmappableAction;
9
10/// Unmappable-input policy used by charset encoders and converters.
11#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
12pub struct CharsetEncodePolicy {
13    /// Action used for unmappable input characters.
14    unmappable_action: UnmappableAction,
15    /// Replacement character used by [`UnmappableAction::Replace`].
16    replacement: char,
17}
18
19impl CharsetEncodePolicy {
20    /// Default replacement character used when unmappable input is replaced.
21    pub const DEFAULT_REPLACEMENT: char = '\u{fffd}';
22    /// Fallback replacement used when the default replacement is unmappable.
23    pub const DEFAULT_FALLBACK_REPLACEMENT: char = '?';
24
25    /// Creates an unmappable-input policy.
26    #[must_use]
27    #[inline(always)]
28    pub const fn new(
29        unmappable_action: UnmappableAction,
30        replacement: char,
31    ) -> Self {
32        Self {
33            unmappable_action,
34            replacement,
35        }
36    }
37
38    /// Creates a replacement policy.
39    #[must_use]
40    #[inline(always)]
41    pub const fn replace(replacement: char) -> Self {
42        Self::new(UnmappableAction::Replace, replacement)
43    }
44
45    /// Creates an ignore policy with the default replacement retained for
46    /// metadata.
47    #[must_use]
48    #[inline(always)]
49    pub const fn ignore() -> Self {
50        Self::ignore_with_replacement(Self::DEFAULT_REPLACEMENT)
51    }
52
53    /// Creates an ignore policy with explicit replacement metadata.
54    #[must_use]
55    #[inline(always)]
56    pub const fn ignore_with_replacement(replacement: char) -> Self {
57        Self::new(UnmappableAction::Ignore, replacement)
58    }
59
60    /// Creates a report policy with the default replacement retained for
61    /// metadata.
62    #[must_use]
63    #[inline(always)]
64    pub const fn report() -> Self {
65        Self::new(UnmappableAction::Report, Self::DEFAULT_REPLACEMENT)
66    }
67
68    /// Returns the unmappable-input action.
69    #[must_use]
70    #[inline(always)]
71    pub const fn unmappable_action(self) -> UnmappableAction {
72        self.unmappable_action
73    }
74
75    /// Returns the replacement character.
76    #[must_use]
77    #[inline(always)]
78    pub const fn replacement(self) -> char {
79        self.replacement
80    }
81}
82
83impl Default for CharsetEncodePolicy {
84    #[inline(always)]
85    fn default() -> Self {
86        Self::replace(Self::DEFAULT_REPLACEMENT)
87    }
88}