qubit_codec_misc/hex_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//! Hexadecimal byte codec.
9
10use qubit_codec::ValueDecoder;
11use qubit_codec::ValueEncoder;
12
13use crate::MiscCodecError;
14use crate::MiscCodecResult;
15use crate::hex_codec_config::HexCodecConfig;
16
17const LOWER_HEX_DIGITS: [char; 16] = [
18 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
19];
20
21const UPPER_HEX_DIGITS: [char; 16] = [
22 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
23];
24
25/// Encodes and decodes hexadecimal byte strings.
26///
27/// `HexCodec` is an owned facade for whole byte slices. Whole-string prefix,
28/// per-byte prefix, separator, and whitespace handling are part of
29/// [`encode`](Self::encode) and [`decode`](Self::decode). Use
30/// [`crate::HexByteCodec`] when a low-level
31/// [`qubit_codec::Codec<Value = u8, Unit = u8>`] is
32/// required.
33#[must_use]
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct HexCodec {
36 config: HexCodecConfig,
37}
38
39impl HexCodec {
40 /// Creates a lowercase codec without prefix or separators.
41 ///
42 /// # Returns
43 /// A hexadecimal codec using lowercase digits.
44 #[inline]
45 pub fn new() -> Self {
46 Self::from_config(HexCodecConfig::new())
47 }
48
49 /// Creates an uppercase codec without prefix or separators.
50 ///
51 /// # Returns
52 /// A hexadecimal codec using uppercase digits.
53 #[inline]
54 pub fn upper() -> Self {
55 Self::from_config(HexCodecConfig::new().with_uppercase(true))
56 }
57
58 /// Creates a codec from an explicit configuration.
59 #[inline]
60 pub fn from_config(config: HexCodecConfig) -> Self {
61 Self { config }
62 }
63
64 /// Returns the configuration used by this codec.
65 #[inline]
66 pub fn config(&self) -> &HexCodecConfig {
67 &self.config
68 }
69
70 /// Sets whether encoded digits should be uppercase.
71 ///
72 /// # Parameters
73 /// - `uppercase`: Whether to use uppercase hexadecimal digits.
74 ///
75 /// # Returns
76 /// The updated codec.
77 #[inline]
78 pub fn with_uppercase(mut self, uppercase: bool) -> Self {
79 self.config = self.config.with_uppercase(uppercase);
80 self
81 }
82
83 /// Sets a whole-output prefix.
84 ///
85 /// The prefix is written once before the encoded bytes and required once
86 /// before decoded input. For example, using prefix `0x` encodes bytes as
87 /// `0x1f8b`.
88 ///
89 /// # Parameters
90 /// - `prefix`: Whole-output prefix text such as `0x`.
91 ///
92 /// # Returns
93 /// The updated codec.
94 #[inline]
95 pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
96 self.config = self.config.with_prefix(prefix);
97 self
98 }
99
100 /// Sets a per-byte prefix.
101 ///
102 /// The prefix is written before every encoded byte and required before
103 /// every decoded byte. For example, using byte prefix `0x` and separator
104 /// ` ` encodes bytes as `0x1f 0x8b`.
105 ///
106 /// # Parameters
107 /// - `prefix`: Per-byte prefix text such as `0x`.
108 ///
109 /// # Returns
110 /// The updated codec.
111 #[inline]
112 pub fn with_byte_prefix(mut self, prefix: impl Into<String>) -> Self {
113 self.config = self.config.with_byte_prefix(prefix);
114 self
115 }
116
117 /// Sets a separator written and accepted between encoded bytes.
118 ///
119 /// # Parameters
120 /// - `separator`: Separator text.
121 ///
122 /// # Returns
123 /// The updated codec.
124 #[inline]
125 pub fn with_separator(mut self, separator: impl Into<String>) -> Self {
126 self.config = self.config.with_separator(separator);
127 self
128 }
129
130 /// Sets whether ASCII whitespace is ignored while decoding.
131 ///
132 /// # Parameters
133 /// - `ignore`: Whether to ignore ASCII whitespace.
134 ///
135 /// # Returns
136 /// The updated codec.
137 #[inline]
138 pub fn with_ignored_ascii_whitespace(mut self, ignore: bool) -> Self {
139 self.config = self.config.with_ignored_ascii_whitespace(ignore);
140 self
141 }
142
143 /// Sets whether ASCII case is ignored when decoding configured prefixes.
144 ///
145 /// This option affects whole-output prefixes and per-byte prefixes during
146 /// decoding only. Encoding writes prefixes exactly as configured.
147 ///
148 /// # Parameters
149 /// - `ignore`: Whether to ignore ASCII case while matching prefixes.
150 ///
151 /// # Returns
152 /// The updated codec.
153 #[inline]
154 pub fn with_ignore_prefix_case(mut self, ignore: bool) -> Self {
155 self.config = self.config.with_ignore_prefix_case(ignore);
156 self
157 }
158
159 /// Encodes bytes into a hexadecimal string.
160 ///
161 /// # Parameters
162 /// - `bytes`: Bytes to encode.
163 ///
164 /// # Returns
165 /// Hexadecimal text.
166 #[inline]
167 #[must_use]
168 pub fn encode(&self, bytes: &[u8]) -> String {
169 let separator_len = self.config.separator.as_ref().map_or(0, String::len);
170 let prefix_len = self.config.prefix.as_ref().map_or(0, String::len);
171 let byte_prefix_len = self.config.byte_prefix.as_ref().map_or(0, String::len);
172 let capacity = prefix_len.saturating_add(
173 bytes
174 .len()
175 .saturating_mul(byte_prefix_len.saturating_add(2))
176 .saturating_add(bytes.len().saturating_sub(1).saturating_mul(separator_len)),
177 );
178 let mut output = String::with_capacity(capacity);
179 self.encode_into(bytes, &mut output);
180 output
181 }
182
183 /// Encodes bytes into an existing string.
184 ///
185 /// # Parameters
186 /// - `bytes`: Bytes to encode.
187 /// - `output`: Destination string.
188 #[inline]
189 pub fn encode_into(&self, bytes: &[u8], output: &mut String) {
190 if let Some(prefix) = &self.config.prefix {
191 output.push_str(prefix);
192 }
193 for (index, byte) in bytes.iter().enumerate() {
194 if index > 0
195 && let Some(separator) = &self.config.separator
196 {
197 output.push_str(separator);
198 }
199 if let Some(byte_prefix) = &self.config.byte_prefix {
200 output.push_str(byte_prefix);
201 }
202 push_hex_byte(*byte, self.config.uppercase, output);
203 }
204 }
205
206 /// Decodes hexadecimal text into bytes.
207 ///
208 /// # Parameters
209 /// - `text`: Hexadecimal text.
210 ///
211 /// # Returns
212 /// Decoded bytes.
213 ///
214 /// # Errors
215 /// Returns [`MiscCodecError`] when a configured whole or per-byte prefix is
216 /// missing, when the normalized digit count is odd, or when a non-hex
217 /// digit is found.
218 #[inline]
219 pub fn decode(&self, text: &str) -> MiscCodecResult<Vec<u8>> {
220 self.decode_to_vec(text)
221 }
222
223 /// Decodes hexadecimal text into an existing byte vector.
224 ///
225 /// # Parameters
226 /// - `text`: Hexadecimal text.
227 /// - `output`: Destination byte vector.
228 ///
229 /// # Errors
230 /// Returns [`MiscCodecError`] when the input is malformed.
231 ///
232 /// # TODO
233 /// This method currently decodes into a temporary vector before appending
234 /// so that an error leaves `output` unchanged. A future optimization can
235 /// decode directly into `output` with a checkpoint-and-rollback strategy,
236 /// or validate and reserve in a first pass, to avoid the temporary vector
237 /// while preserving transactional behavior.
238 #[inline]
239 pub fn decode_into(&self, text: &str, output: &mut Vec<u8>) -> MiscCodecResult<()> {
240 let decoded = self.decode_to_vec(text)?;
241 output.reserve(decoded.len());
242 output.extend(decoded);
243 Ok(())
244 }
245
246 /// Decodes text into a new byte vector using a single transactional pass.
247 ///
248 /// # Parameters
249 /// - `text`: Text to decode.
250 ///
251 /// # Returns
252 /// Decoded bytes.
253 ///
254 /// # Errors
255 /// Returns [`MiscCodecError::InvalidDigit`] for unsupported characters.
256 #[inline]
257 fn decode_to_vec(&self, text: &str) -> MiscCodecResult<Vec<u8>> {
258 let start_index = self.consume_prefix(text)?;
259 if let Some(separator) = self
260 .config
261 .separator
262 .as_deref()
263 .filter(|separator| !separator.is_empty())
264 {
265 return self.decode_separated(text, start_index, separator);
266 }
267 if let Some(byte_prefix) = self.config.byte_prefix.as_deref().filter(|prefix| !prefix.is_empty()) {
268 return self.decode_byte_prefixed(text, byte_prefix, start_index);
269 }
270 self.decode_unprefixed(text, start_index)
271 }
272
273 /// Consumes the configured whole-output prefix.
274 ///
275 /// # Parameters
276 /// - `text`: Text to decode.
277 ///
278 /// # Returns
279 /// Byte index where byte parsing should start.
280 ///
281 /// # Errors
282 /// Returns [`MiscCodecError::MissingPrefix`] when a non-empty whole-output
283 /// prefix is configured but absent.
284 #[inline]
285 fn consume_prefix(&self, text: &str) -> MiscCodecResult<usize> {
286 let Some(prefix) = self.config.prefix.as_deref().filter(|prefix| !prefix.is_empty()) else {
287 return Ok(0);
288 };
289 let index = if self.starts_with_prefix(text, prefix) {
290 0
291 } else {
292 self.skip_ascii_whitespace(text, 0)
293 };
294 let rest = &text[index..];
295 if self.starts_with_prefix(rest, prefix) {
296 Ok(index + prefix.len())
297 } else {
298 Err(MiscCodecError::MissingPrefix {
299 prefix: prefix.to_owned(),
300 })
301 }
302 }
303
304 /// Decodes separator-delimited input into bytes.
305 ///
306 /// # Parameters
307 /// - `text`: Text to decode.
308 /// - `index`: Byte index where parsing should start.
309 /// - `separator`: Required separator between complete bytes.
310 ///
311 /// # Returns
312 /// Decoded bytes.
313 ///
314 /// # Errors
315 /// Returns [`MiscCodecError`] when a byte is malformed or the configured
316 /// separator is missing between complete bytes.
317 fn decode_separated(&self, text: &str, mut index: usize, separator: &str) -> MiscCodecResult<Vec<u8>> {
318 let mut output = Vec::with_capacity(text.len() / 2);
319 index = self.skip_ascii_whitespace(text, index);
320 if index >= text.len() {
321 return Ok(output);
322 }
323 loop {
324 index = self.consume_byte_prefix(text, index)?;
325 let (_, high_char, next_index) = read_required_hex_digit(text, index)?;
326 let (_, low_char, next_index) = read_required_hex_digit(text, next_index)?;
327 output.push(decode_hex_pair(high_char, low_char));
328 index = next_index;
329
330 let separator_index = self.next_separator_index(text, index, separator);
331 if separator_index >= text.len() {
332 return Ok(output);
333 }
334 let rest = &text[separator_index..];
335 if !rest.starts_with(separator) {
336 return Err(invalid_hex_input(&format!(
337 "missing separator '{separator}' between hex bytes"
338 )));
339 }
340 index = self.skip_ascii_whitespace(text, separator_index + separator.len());
341 if index >= text.len() {
342 return Err(invalid_hex_input("separator must be followed by a hex byte"));
343 }
344 }
345 }
346
347 /// Consumes the configured per-byte prefix.
348 ///
349 /// # Parameters
350 /// - `text`: Text to decode.
351 /// - `index`: Current byte index.
352 ///
353 /// # Returns
354 /// Index after the per-byte prefix, or `index` when no non-empty per-byte
355 /// prefix is configured.
356 ///
357 /// # Errors
358 /// Returns [`MiscCodecError::MissingPrefix`] when the configured per-byte
359 /// prefix is absent.
360 #[inline]
361 fn consume_byte_prefix(&self, text: &str, index: usize) -> MiscCodecResult<usize> {
362 let Some(prefix) = self.config.byte_prefix.as_deref().filter(|prefix| !prefix.is_empty()) else {
363 return Ok(index);
364 };
365 let index = if self.starts_with_prefix(&text[index..], prefix) {
366 index
367 } else {
368 self.skip_ignored(text, index)
369 };
370 let rest = &text[index..];
371 if self.starts_with_prefix(rest, prefix) {
372 Ok(index + prefix.len())
373 } else {
374 Err(MiscCodecError::MissingPrefix {
375 prefix: prefix.to_owned(),
376 })
377 }
378 }
379
380 /// Finds the position where the next separator must appear.
381 ///
382 /// # Parameters
383 /// - `text`: Text being decoded.
384 /// - `index`: Current byte index after a complete hex byte.
385 /// - `separator`: Configured separator.
386 ///
387 /// # Returns
388 /// Index where the separator must start, or `text.len()` when only ignored
389 /// trailing whitespace remains.
390 #[inline]
391 fn next_separator_index(&self, text: &str, index: usize, separator: &str) -> usize {
392 if !separator.chars().all(|ch| ch.is_ascii_whitespace())
393 && text.get(index..).is_some_and(|rest| rest.starts_with(separator))
394 {
395 return index;
396 }
397 let whitespace_end = self.skip_ascii_whitespace(text, index);
398 if whitespace_end >= text.len() {
399 return whitespace_end;
400 }
401 if separator.chars().all(|ch| ch.is_ascii_whitespace()) {
402 index
403 } else {
404 whitespace_end
405 }
406 }
407
408 /// Decodes unprefixed input characters into bytes.
409 ///
410 /// # Parameters
411 /// - `text`: Text to decode.
412 ///
413 /// # Returns
414 /// Decoded bytes.
415 ///
416 /// # Errors
417 /// Returns [`MiscCodecError::InvalidDigit`] for unsupported characters.
418 fn decode_unprefixed(&self, text: &str, mut index: usize) -> MiscCodecResult<Vec<u8>> {
419 let mut output = Vec::with_capacity(text.len() / 2);
420 let mut pending = None;
421 let mut digit_count = 0usize;
422 while index < text.len() {
423 let rest = &text[index..];
424 let ch = rest.chars().next().expect("index is below text length");
425 if self.config.ignore_ascii_whitespace && ch.is_ascii_whitespace() {
426 index += ch.len_utf8();
427 continue;
428 }
429 if hex_value(ch).is_some() {
430 digit_count += 1;
431 if let Some(high_char) = pending.take() {
432 output.push(decode_hex_pair(high_char, ch));
433 } else {
434 pending = Some(ch);
435 }
436 index += ch.len_utf8();
437 continue;
438 }
439 return Err(invalid_hex_digit(index, ch));
440 }
441 if !digit_count.is_multiple_of(2) {
442 return Err(invalid_hex_length(digit_count));
443 }
444 Ok(output)
445 }
446
447 /// Decodes byte-prefixed input characters into bytes.
448 ///
449 /// # Parameters
450 /// - `text`: Text to decode.
451 /// - `prefix`: Required prefix before each byte.
452 /// - `index`: Byte index where parsing should start.
453 ///
454 /// # Returns
455 /// Decoded bytes.
456 ///
457 /// # Errors
458 /// Returns [`MiscCodecError::MissingPrefix`] when a byte prefix is missing,
459 /// or [`MiscCodecError::InvalidDigit`] for unsupported characters.
460 fn decode_byte_prefixed(&self, text: &str, prefix: &str, mut index: usize) -> MiscCodecResult<Vec<u8>> {
461 let mut output = Vec::with_capacity(text.len() / 2);
462 let mut digit_count = 0usize;
463 while index < text.len() {
464 index = self.skip_ignored(text, index);
465 if index >= text.len() {
466 break;
467 }
468 let rest = &text[index..];
469 if !self.starts_with_prefix(rest, prefix) {
470 return Err(MiscCodecError::MissingPrefix {
471 prefix: prefix.to_owned(),
472 });
473 }
474 index += prefix.len();
475
476 let mut pair_count = 0;
477 let mut pair = [(0usize, '\0'); 2];
478 while pair_count < 2 && index < text.len() {
479 let rest = &text[index..];
480 let ch = rest.chars().next().expect("index is below text length");
481 if self.config.ignore_ascii_whitespace && ch.is_ascii_whitespace() {
482 index += ch.len_utf8();
483 continue;
484 }
485 if hex_value(ch).is_some() {
486 pair[pair_count] = (index, ch);
487 index += ch.len_utf8();
488 pair_count += 1;
489 digit_count += 1;
490 continue;
491 }
492 return Err(invalid_hex_digit(index, ch));
493 }
494 if pair_count != 2 {
495 return Err(invalid_hex_input("byte prefix must be followed by two hex digits"));
496 }
497 output.push(decode_hex_pair(pair[0].1, pair[1].1));
498 }
499 if !digit_count.is_multiple_of(2) {
500 return Err(invalid_hex_length(digit_count));
501 }
502 Ok(output)
503 }
504
505 /// Skips ignored ASCII whitespace.
506 ///
507 /// # Parameters
508 /// - `text`: Text being decoded.
509 /// - `index`: Current byte index.
510 ///
511 /// # Returns
512 /// The next byte index that should be parsed.
513 #[inline]
514 fn skip_ignored(&self, text: &str, mut index: usize) -> usize {
515 while index < text.len() {
516 let byte = text.as_bytes()[index];
517 if self.config.ignore_ascii_whitespace && byte.is_ascii_whitespace() {
518 index += 1;
519 continue;
520 }
521 return index;
522 }
523 index
524 }
525
526 /// Skips ignored leading ASCII whitespace.
527 ///
528 /// # Parameters
529 /// - `text`: Text being decoded.
530 /// - `index`: Current byte index.
531 ///
532 /// # Returns
533 /// The next byte index after ignored ASCII whitespace.
534 #[inline]
535 fn skip_ascii_whitespace(&self, text: &str, mut index: usize) -> usize {
536 while self.config.ignore_ascii_whitespace && index < text.len() {
537 if !text.as_bytes()[index].is_ascii_whitespace() {
538 return index;
539 }
540 index += 1;
541 }
542 index
543 }
544
545 /// Tests whether `text` starts with a configured prefix.
546 ///
547 /// # Parameters
548 /// - `text`: Text slice to inspect.
549 /// - `prefix`: Configured prefix.
550 ///
551 /// # Returns
552 /// `true` when `text` starts with `prefix`, honoring the configured
553 /// ASCII case sensitivity for decoding prefixes.
554 #[inline]
555 fn starts_with_prefix(&self, text: &str, prefix: &str) -> bool {
556 if !self.config.ignore_prefix_case {
557 return text.starts_with(prefix);
558 }
559 let Some(candidate) = text.get(..prefix.len()) else {
560 return false;
561 };
562 candidate.eq_ignore_ascii_case(prefix)
563 }
564}
565
566impl Default for HexCodec {
567 /// Creates a lowercase codec without prefix or separators.
568 #[inline]
569 fn default() -> Self {
570 Self::new()
571 }
572}
573
574impl ValueEncoder<[u8]> for HexCodec {
575 type Error = MiscCodecError;
576 type Output = String;
577
578 /// Encodes bytes into hexadecimal text.
579 #[inline]
580 fn encode(&mut self, input: &[u8]) -> Result<Self::Output, Self::Error> {
581 Ok(HexCodec::encode(self, input))
582 }
583}
584
585impl ValueDecoder<str> for HexCodec {
586 type Error = MiscCodecError;
587 type Output = Vec<u8>;
588
589 /// Decodes hexadecimal text into bytes.
590 #[inline]
591 fn decode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
592 HexCodec::decode(self, input)
593 }
594}
595
596/// Converts one hex digit to its value.
597///
598/// # Parameters
599/// - `ch`: Character to inspect.
600///
601/// # Returns
602/// Nibble value, or `None` when `ch` is not a hex digit.
603#[inline(always)]
604pub(crate) fn hex_value(ch: char) -> Option<u8> {
605 match ch {
606 '0'..='9' => Some(ch as u8 - b'0'),
607 'a'..='f' => Some(ch as u8 - b'a' + 10),
608 'A'..='F' => Some(ch as u8 - b'A' + 10),
609 _ => None,
610 }
611}
612
613/// Builds an invalid hexadecimal digit error.
614///
615/// # Parameters
616/// - `index`: Byte index of the invalid character in the original input.
617/// - `character`: Invalid character.
618///
619/// # Returns
620/// A radix-16 digit error.
621pub(crate) fn invalid_hex_digit(index: usize, character: char) -> MiscCodecError {
622 MiscCodecError::InvalidDigit {
623 radix: 16,
624 index,
625 character,
626 }
627}
628
629/// Builds an invalid hexadecimal length error.
630///
631/// # Parameters
632/// - `actual`: Number of normalized hexadecimal digits.
633///
634/// # Returns
635/// An invalid length error describing the even-digit requirement.
636fn invalid_hex_length(actual: usize) -> MiscCodecError {
637 MiscCodecError::InvalidLength {
638 context: "hex digits",
639 expected: "an even number of digits".to_owned(),
640 actual,
641 }
642}
643
644/// Builds an invalid hexadecimal input error.
645///
646/// # Parameters
647/// - `reason`: Human-readable reason the input was rejected.
648///
649/// # Returns
650/// An invalid input error for the hexadecimal codec.
651fn invalid_hex_input(reason: &str) -> MiscCodecError {
652 MiscCodecError::InvalidInput {
653 codec: "hex",
654 reason: reason.to_owned(),
655 }
656}
657
658/// Reads one required hexadecimal digit at a byte boundary.
659///
660/// # Parameters
661/// - `text`: Text being decoded.
662/// - `index`: Byte index where the digit is expected.
663///
664/// # Returns
665/// Original digit index, digit character, and the next byte index.
666///
667/// # Errors
668/// Returns [`MiscCodecError::InvalidInput`] when input ends before the digit,
669/// or [`MiscCodecError::InvalidDigit`] when the next character is not hex.
670#[inline]
671fn read_required_hex_digit(text: &str, index: usize) -> MiscCodecResult<(usize, char, usize)> {
672 let rest = &text[index..];
673 let Some(character) = rest.chars().next() else {
674 return Err(invalid_hex_input("expected a hexadecimal digit"));
675 };
676 if hex_value(character).is_none() {
677 return Err(invalid_hex_digit(index, character));
678 }
679 Ok((index, character, index + character.len_utf8()))
680}
681
682/// Decodes two hexadecimal characters into one byte.
683///
684/// # Parameters
685/// - `high_index`: Original byte index of the high nibble.
686/// - `high_char`: High-nibble character.
687/// - `low_index`: Original byte index of the low nibble.
688/// - `low_char`: Low-nibble character.
689///
690/// # Returns
691/// The decoded byte.
692///
693/// The callers validate both characters before constructing the pair.
694#[inline]
695fn decode_hex_pair(high_char: char, low_char: char) -> u8 {
696 let high = hex_value(high_char).expect("validated hexadecimal digit");
697 let low = hex_value(low_char).expect("validated hexadecimal digit");
698 (high << 4) | low
699}
700
701/// Appends one encoded byte to `output`.
702///
703/// # Parameters
704/// - `byte`: Byte to encode.
705/// - `uppercase`: Whether to use uppercase digits.
706/// - `output`: Destination string.
707#[inline(always)]
708fn push_hex_byte(byte: u8, uppercase: bool, output: &mut String) {
709 output.push(hex_digit(byte >> 4, uppercase));
710 output.push(hex_digit(byte & 0x0f, uppercase));
711}
712
713/// Converts one nibble to a hexadecimal digit.
714///
715/// # Parameters
716/// - `value`: Nibble value.
717/// - `uppercase`: Whether to use uppercase digits.
718///
719/// # Returns
720/// Hexadecimal digit. Values above `0x0f` are masked to their low nibble.
721#[inline(always)]
722pub(crate) fn hex_digit(value: u8, uppercase: bool) -> char {
723 let digits = if uppercase {
724 &UPPER_HEX_DIGITS
725 } else {
726 &LOWER_HEX_DIGITS
727 };
728 digits[(value & 0x0f) as usize]
729}