Skip to main content

qubit_codec_misc/
hex_byte_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 hexadecimal byte codec.
9
10use core::num::NonZeroUsize;
11
12use qubit_codec::Codec;
13use qubit_codec::DecodeFailure;
14use qubit_utils::nonzero;
15
16use crate::MiscCodecError;
17use crate::hex::hex_digit;
18use crate::hex::hex_value;
19use crate::hex::invalid_hex_digit;
20use crate::misc_error::map_misc_decode_failure_with_consumed;
21
22/// Encodes and decodes one byte as two ASCII hexadecimal units.
23///
24/// `HexByteCodec` is the low-level [`Codec`] implementation for streaming or
25/// generic codec call sites. It does not understand whole-string prefixes,
26/// per-byte prefixes, separators, or whitespace. Use [`crate::HexCodec`] for
27/// owned byte-slice helpers with those formatting options.
28///
29/// For a complete safe streaming adapter example, see the [English README](https://github.com/qubit-ltd/rs-codec-misc/blob/main/README.md#safe-streaming-hex-byte-adapter)
30/// and [Chinese README](https://github.com/qubit-ltd/rs-codec-misc/blob/main/README.zh_CN.md#安全的-hex-字节流式-adapter).
31///
32/// # Examples
33///
34/// ```
35/// use qubit_codec::Codec;
36/// use qubit_codec_misc::HexByteCodec;
37///
38/// let mut codec = HexByteCodec::upper();
39/// let mut output = [0_u8; 2];
40/// let written = unsafe { Codec::encode(&mut codec, &0xaf, &mut output, 0) }?;
41///
42/// assert_eq!(2, written);
43/// assert_eq!(b"AF", &output);
44/// # Ok::<(), qubit_codec_misc::MiscCodecError>(())
45/// ```
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub struct HexByteCodec {
48    /// Controls whether encoded hexadecimal digits use uppercase letters.
49    uppercase: bool,
50}
51
52impl HexByteCodec {
53    /// Creates a lowercase single-byte hexadecimal codec.
54    #[must_use]
55    #[inline]
56    pub const fn new() -> Self {
57        Self { uppercase: false }
58    }
59
60    /// Creates an uppercase single-byte hexadecimal codec.
61    #[must_use]
62    #[inline]
63    pub const fn upper() -> Self {
64        Self { uppercase: true }
65    }
66
67    /// Returns whether this byte codec emits uppercase hexadecimal digits.
68    #[must_use]
69    #[inline]
70    pub const fn is_uppercase(self) -> bool {
71        self.uppercase
72    }
73
74    /// Sets whether encoded digits should be uppercase.
75    #[must_use]
76    #[inline]
77    pub const fn with_uppercase(mut self, uppercase: bool) -> Self {
78        self.uppercase = uppercase;
79        self
80    }
81}
82
83impl Codec for HexByteCodec {
84    type Value = u8;
85    type Unit = u8;
86    type DecodeError = MiscCodecError;
87    type EncodeError = MiscCodecError;
88
89    const MIN_UNITS_PER_VALUE: usize = 2;
90    const MAX_ENCODE_UNITS_PER_VALUE: usize = 2;
91    const MAX_DECODE_UNITS_PER_VALUE: usize = 2;
92
93    /// Decodes one byte from two ASCII hexadecimal digits.
94    ///
95    /// The digits are read from `input` starting at `input_index`. Invalid
96    /// digits are reported with their position in the input.
97    ///
98    /// # Parameters
99    ///
100    /// - `input`: The byte units containing the hexadecimal digits.
101    /// - `input_index`: The index of the first digit.
102    ///
103    /// # Returns
104    ///
105    /// The decoded byte and the nonzero number of input units consumed (two).
106    ///
107    /// # Errors
108    ///
109    /// Returns a decode failure when either input unit is not an ASCII
110    /// hexadecimal digit. The failure identifies the invalid digit and its
111    /// input position.
112    ///
113    /// # Safety
114    /// `input` must contain at least two readable units starting at
115    /// `input_index`.
116    #[inline]
117    unsafe fn decode(
118        &mut self,
119        input: &[u8],
120        input_index: usize,
121    ) -> Result<(u8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
122        debug_assert!(input_index + 2 <= input.len());
123
124        let high_char = char::from(input[input_index]);
125        let low_char = char::from(input[input_index + 1]);
126        let high = hex_value(high_char)
127            .ok_or_else(|| invalid_hex_digit(input_index, high_char))
128            .map_err(|error| map_misc_decode_failure_with_consumed(error, nonzero(2)))?;
129        let low = hex_value(low_char)
130            .ok_or_else(|| invalid_hex_digit(input_index + 1, low_char))
131            .map_err(|error| map_misc_decode_failure_with_consumed(error, nonzero(2)))?;
132        Ok(((high << 4) | low, nonzero(2)))
133    }
134
135    /// Encodes one byte as two ASCII hexadecimal digits.
136    ///
137    /// # Parameters
138    ///
139    /// - `value`: The byte to encode.
140    /// - `output`: The buffer that receives the encoded digits.
141    /// - `output_index`: The index of the first output unit to write.
142    ///
143    /// # Returns
144    ///
145    /// The number of output units written (two).
146    ///
147    /// # Errors
148    ///
149    /// This implementation does not return an encoding error; the result is
150    /// retained to satisfy the [`Codec`] interface.
151    ///
152    /// # Safety
153    /// `output` must contain at least two writable units starting at
154    /// `output_index`.
155    #[inline]
156    unsafe fn encode(
157        &mut self,
158        value: &u8,
159        output: &mut [u8],
160        output_index: usize,
161    ) -> Result<usize, Self::EncodeError> {
162        debug_assert!(output_index + 2 <= output.len());
163
164        output[output_index] = hex_digit(*value >> 4, self.uppercase) as u8;
165        output[output_index + 1] = hex_digit(*value & 0x0f, self.uppercase) as u8;
166        Ok(2)
167    }
168}