Skip to main content

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