qubit-codec-misc 0.8.4

Miscellaneous byte and text format codecs for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Hexadecimal byte codec.

use qubit_codec::ValueDecoder;
use qubit_codec::ValueEncoder;

use crate::MiscCodecError;
use crate::MiscCodecResult;
use crate::hex_codec_config::HexCodecConfig;

const LOWER_HEX_DIGITS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];

const UPPER_HEX_DIGITS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
];

/// Encodes and decodes hexadecimal byte strings.
///
/// `HexCodec` is an owned facade for whole byte slices. Whole-string prefix,
/// per-byte prefix, separator, and whitespace handling are part of
/// [`encode`](Self::encode) and [`decode`](Self::decode). Use
/// [`crate::HexByteCodec`] when a low-level
/// [`qubit_codec::Codec<Value = u8, Unit = u8>`] is
/// required.
///
/// # Examples
///
/// ```
/// use qubit_codec_misc::HexCodec;
///
/// let codec = HexCodec::new();
/// let encoded = codec.encode(&[0x1f, 0x8b]);
/// assert_eq!(encoded, "1f8b");
/// assert_eq!(codec.decode(&encoded).unwrap(), [0x1f, 0x8b]);
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HexCodec {
    /// Configuration shared by whole-slice encoding and decoding operations.
    config: HexCodecConfig,
}

impl HexCodec {
    /// Creates a lowercase codec without prefix or separators.
    ///
    /// # Returns
    /// A hexadecimal codec using lowercase digits.
    #[inline]
    pub fn new() -> Self {
        Self::from_config(HexCodecConfig::new())
    }

    /// Creates an uppercase codec without prefix or separators.
    ///
    /// # Returns
    /// A hexadecimal codec using uppercase digits.
    #[inline]
    pub fn upper() -> Self {
        Self::from_config(HexCodecConfig::new().with_uppercase(true))
    }

    /// Creates a codec from an explicit configuration.
    ///
    /// # Parameters
    /// - `config`: Configuration moved into the codec without cloning.
    ///
    /// # Returns
    /// A codec owning the supplied configuration.
    #[inline]
    pub fn from_config(config: HexCodecConfig) -> Self {
        Self { config }
    }

    /// Returns the configuration used by this codec.
    ///
    /// # Returns
    /// A shared reference to this codec's configuration, borrowed from `self`.
    #[must_use = "inspect the configuration or retain the reference for later use"]
    #[inline]
    pub fn config(&self) -> &HexCodecConfig {
        &self.config
    }

    /// Sets whether encoded digits should be uppercase.
    ///
    /// # Parameters
    /// - `uppercase`: Whether to use uppercase hexadecimal digits.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_uppercase(mut self, uppercase: bool) -> Self {
        self.config = self.config.with_uppercase(uppercase);
        self
    }

    /// Sets a whole-output prefix.
    ///
    /// The prefix is written once before the encoded bytes and required once
    /// before decoded input. For example, using prefix `0x` encodes bytes as
    /// `0x1f8b`.
    ///
    /// # Parameters
    /// - `prefix`: Whole-output prefix text such as `0x`.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config = self.config.with_prefix(prefix);
        self
    }

    /// Sets a per-byte prefix.
    ///
    /// The prefix is written before every encoded byte and required before
    /// every decoded byte. For example, using byte prefix `0x` and separator
    /// ` ` encodes bytes as `0x1f 0x8b`.
    /// When ASCII whitespace is ignored, a complete per-byte prefix is matched
    /// before additional whitespace is skipped.
    ///
    /// # Parameters
    /// - `prefix`: Per-byte prefix text such as `0x`.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_byte_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config = self.config.with_byte_prefix(prefix);
        self
    }

    /// Sets a separator written and accepted between encoded bytes.
    ///
    /// With a non-empty separator, the two hexadecimal digits of each byte
    /// must be contiguous. Ignored ASCII whitespace may surround complete
    /// byte tokens and configured separators, but does not replace a required
    /// prefix or separator. Without a non-empty separator, ignored whitespace
    /// may also occur between the two digits of a byte. A complete structural
    /// token is matched before skipping additional whitespace. Non-whitespace
    /// separators are matched exactly; a whitespace-only separator still
    /// requires whitespace between bytes, and ignored ASCII whitespace may
    /// consume additional adjacent whitespace. Prefix case folding does not
    /// apply to separators.
    ///
    /// # Parameters
    /// - `separator`: Separator text.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_separator(mut self, separator: impl Into<String>) -> Self {
        self.config = self.config.with_separator(separator);
        self
    }

    /// Sets whether ASCII whitespace is ignored while decoding.
    ///
    /// With a non-empty separator, the two hexadecimal digits of each byte
    /// must be contiguous. Ignored ASCII whitespace may surround complete
    /// byte tokens and configured separators, but does not replace a required
    /// prefix or separator. Without a non-empty separator, ignored whitespace
    /// may also occur between the two digits of a byte. A complete structural
    /// token is matched before skipping additional whitespace. Non-whitespace
    /// separators are matched exactly; a whitespace-only separator still
    /// requires whitespace between bytes, and ignored ASCII whitespace may
    /// consume additional adjacent whitespace. Prefix case folding does not
    /// apply to separators.
    ///
    /// # Parameters
    /// - `ignore`: Whether to ignore ASCII whitespace.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_ignored_ascii_whitespace(mut self, ignore: bool) -> Self {
        self.config = self.config.with_ignored_ascii_whitespace(ignore);
        self
    }

    /// Sets whether ASCII case is ignored when decoding configured prefixes.
    ///
    /// This option affects whole-output prefixes and per-byte prefixes during
    /// decoding only. Encoding writes prefixes exactly as configured.
    ///
    /// # Parameters
    /// - `ignore`: Whether to ignore ASCII case while matching prefixes.
    ///
    /// # Returns
    /// The updated codec.
    #[inline]
    pub fn with_ignore_prefix_case(mut self, ignore: bool) -> Self {
        self.config = self.config.with_ignore_prefix_case(ignore);
        self
    }

    /// Encodes bytes into a hexadecimal string.
    ///
    /// # Parameters
    /// - `bytes`: Bytes to encode.
    ///
    /// # Returns
    /// Hexadecimal text.
    #[inline]
    #[must_use]
    pub fn encode(&self, bytes: &[u8]) -> String {
        let separator_len = self.config.separator.as_ref().map_or(0, String::len);
        let prefix_len = self.config.prefix.as_ref().map_or(0, String::len);
        let byte_prefix_len = self.config.byte_prefix.as_ref().map_or(0, String::len);
        let capacity = prefix_len.saturating_add(
            bytes
                .len()
                .saturating_mul(byte_prefix_len.saturating_add(2))
                .saturating_add(bytes.len().saturating_sub(1).saturating_mul(separator_len)),
        );
        let mut output = String::with_capacity(capacity);
        self.encode_into(bytes, &mut output);
        output
    }

    /// Appends the hexadecimal encoding of bytes to an existing string.
    ///
    /// Existing contents are preserved. Call `output.clear()` first to
    /// replace them. Each call writes its own configured whole-output prefix;
    /// no separator is inserted between existing contents and this call's
    /// output.
    ///
    /// # Parameters
    /// - `bytes`: Bytes to encode.
    /// - `output`: Destination string to append to.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_codec_misc::HexCodec;
    /// let codec = HexCodec::new();
    /// let mut output = String::from("header:");
    /// codec.encode_into(&[0xab], &mut output);
    /// assert_eq!(output, "header:ab");
    /// output.clear();
    /// codec.encode_into(&[0xcd], &mut output);
    /// assert_eq!(output, "cd");
    /// ```
    #[inline]
    pub fn encode_into(&self, bytes: &[u8], output: &mut String) {
        if let Some(prefix) = &self.config.prefix {
            output.push_str(prefix);
        }
        for (index, byte) in bytes.iter().enumerate() {
            if index > 0
                && let Some(separator) = &self.config.separator
            {
                output.push_str(separator);
            }
            if let Some(byte_prefix) = &self.config.byte_prefix {
                output.push_str(byte_prefix);
            }
            push_hex_byte(*byte, self.config.uppercase, output);
        }
    }

    /// Decodes hexadecimal text into bytes.
    ///
    /// # Parameters
    /// - `text`: Hexadecimal text.
    ///
    /// # Returns
    /// Decoded bytes.
    ///
    /// # Errors
    /// Returns [`MiscCodecError`] when a configured whole or per-byte prefix is
    /// missing, when the normalized digit count is odd, or when a non-hex
    /// digit is found.
    #[inline]
    pub fn decode(&self, text: &str) -> MiscCodecResult<Vec<u8>> {
        let mut output = Vec::new();
        self.decode_into(text, &mut output)?;
        Ok(output)
    }

    /// Appends decoded hexadecimal bytes to an existing vector.
    ///
    /// Successful calls append decoded bytes. Call `output.clear()` first to
    /// replace existing contents. If decoding fails, elements and length from
    /// before this call are restored, though capacity may change. Contents
    /// cleared by the caller before this call are not protected by rollback.
    ///
    /// # Parameters
    /// - `text`: Hexadecimal text.
    /// - `output`: Destination byte vector to append to.
    ///
    /// # Errors
    /// Returns [`MiscCodecError`] when the input is malformed. On such an
    /// error, the vector's elements and length remain unchanged; its capacity
    /// may have changed.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_codec_misc::HexCodec;
    /// let codec = HexCodec::new();
    /// let mut output = vec![0xa5];
    /// codec.decode_into("ab", &mut output).unwrap();
    /// assert_eq!(output, [0xa5, 0xab]);
    /// assert!(codec.decode_into("cd0g", &mut output).is_err());
    /// assert_eq!(output, [0xa5, 0xab]);
    /// output.clear();
    /// codec.decode_into("cd", &mut output).unwrap();
    /// assert_eq!(output, [0xcd]);
    /// ```
    #[inline]
    pub fn decode_into(&self, text: &str, output: &mut Vec<u8>) -> MiscCodecResult<()> {
        let original_len = output.len();
        if let Err(error) = self.decode_append(text, output) {
            output.truncate(original_len);
            return Err(error);
        }
        Ok(())
    }

    /// Decodes text by appending bytes directly to `output`.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    /// - `output`: Destination byte vector, which may contain existing bytes.
    ///
    /// # Returns
    /// `Ok(())` when all bytes are decoded.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::MissingPrefix`] when a configured prefix is
    /// absent, [`MiscCodecError::InvalidLength`] for an odd digit count,
    /// [`MiscCodecError::InvalidDigit`] for unsupported characters, or
    /// [`MiscCodecError::InvalidInput`] for malformed separator syntax.
    #[inline]
    fn decode_append(&self, text: &str, output: &mut Vec<u8>) -> MiscCodecResult<()> {
        let start_index = self.consume_prefix(text)?;
        let is_plain = !self.config.ignore_ascii_whitespace
            && self.config.byte_prefix.as_deref().is_none_or(str::is_empty)
            && self.config.separator.as_deref().is_none_or(str::is_empty);
        if is_plain {
            output.reserve(text.len().saturating_sub(start_index) / 2);
        }
        if let Some(separator) = self
            .config
            .separator
            .as_deref()
            .filter(|separator| !separator.is_empty())
        {
            return self.decode_separated(text, start_index, separator, output);
        }
        if let Some(byte_prefix) = self.config.byte_prefix.as_deref().filter(|prefix| !prefix.is_empty()) {
            return self.decode_byte_prefixed(text, byte_prefix, start_index, output);
        }
        self.decode_unprefixed(text, start_index, output)
    }

    /// Consumes the configured whole-output prefix.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    ///
    /// # Returns
    /// Byte index where byte parsing should start.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::MissingPrefix`] when a non-empty whole-output
    /// prefix is configured but absent.
    ///
    /// A complete configured prefix is matched before ignored ASCII whitespace
    /// is skipped, so whitespace that belongs to the prefix is preserved.
    #[inline]
    fn consume_prefix(&self, text: &str) -> MiscCodecResult<usize> {
        let Some(prefix) = self.config.prefix.as_deref().filter(|prefix| !prefix.is_empty()) else {
            return Ok(0);
        };
        let mut index = 0;
        loop {
            if self.starts_with_prefix(&text[index..], prefix) {
                return Ok(index + prefix.len());
            }
            if !self.config.ignore_ascii_whitespace
                || index == text.len()
                || !text.as_bytes()[index].is_ascii_whitespace()
            {
                return Err(MiscCodecError::MissingPrefix {
                    prefix: prefix.to_owned(),
                });
            }
            index += 1;
        }
    }

    /// Decodes separator-delimited input into bytes.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    /// - `index`: Byte index where parsing should start.
    /// - `separator`: Required separator between complete bytes.
    /// - `output`: Existing buffer to which decoded bytes are appended; an
    ///   error may leave bytes appended before the failure.
    ///
    /// # Returns
    /// `Ok(())` when all bytes are decoded.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::MissingPrefix`] when a configured per-byte
    /// prefix is absent, or [`MiscCodecError::InvalidInput`] when a byte or
    /// separator syntax is malformed.
    fn decode_separated(
        &self,
        text: &str,
        mut index: usize,
        separator: &str,
        output: &mut Vec<u8>,
    ) -> MiscCodecResult<()> {
        index = self.next_byte_start(text, index);
        if index >= text.len() {
            return Ok(());
        }
        loop {
            index = self.consume_byte_prefix(text, index)?;
            let (_, high_char, next_index) = read_required_hex_digit(text, index)?;
            let (_, low_char, next_index) = read_required_hex_digit(text, next_index)?;
            output.push(decode_hex_pair(high_char, low_char));
            index = next_index;

            let separator_index = self.next_separator_index(text, index, separator);
            if separator_index >= text.len() {
                return Ok(());
            }
            let rest = &text[separator_index..];
            if !rest.starts_with(separator) {
                return Err(invalid_hex_input(&format!(
                    "missing separator '{separator}' between hex bytes"
                )));
            }
            index = self.next_byte_start(text, separator_index + separator.len());
            if index >= text.len() {
                return Err(invalid_hex_input("separator must be followed by a hex byte"));
            }
        }
    }

    /// Consumes the configured per-byte prefix.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    /// - `index`: Current byte index.
    ///
    /// # Returns
    /// Index after the per-byte prefix, or `index` when no non-empty per-byte
    /// prefix is configured.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::MissingPrefix`] when the configured per-byte
    /// prefix is absent.
    #[inline]
    fn consume_byte_prefix(&self, text: &str, index: usize) -> MiscCodecResult<usize> {
        let Some(prefix) = self.config.byte_prefix.as_deref().filter(|prefix| !prefix.is_empty()) else {
            return Ok(index);
        };
        let index = if self.starts_with_prefix(&text[index..], prefix) {
            index
        } else {
            self.skip_ignored(text, index)
        };
        let rest = &text[index..];
        if self.starts_with_prefix(rest, prefix) {
            Ok(index + prefix.len())
        } else {
            Err(MiscCodecError::MissingPrefix {
                prefix: prefix.to_owned(),
            })
        }
    }

    /// Finds the position where the next separator must appear.
    ///
    /// # Parameters
    /// - `text`: Text being decoded.
    /// - `index`: Current byte index after a complete hex byte.
    /// - `separator`: Configured separator.
    ///
    /// # Returns
    /// Index where the separator must start, or `text.len()` when only ignored
    /// trailing whitespace remains.
    #[must_use]
    #[inline]
    fn next_separator_index(&self, text: &str, index: usize, separator: &str) -> usize {
        if separator.chars().all(|ch| ch.is_ascii_whitespace()) {
            let whitespace_end = self.skip_ascii_whitespace(text, index);
            if whitespace_end >= text.len() {
                return whitespace_end;
            }
        }
        let mut candidate = index;
        while candidate < text.len() {
            if text[candidate..].starts_with(separator) {
                return candidate;
            }
            if !self.config.ignore_ascii_whitespace || !text.as_bytes()[candidate].is_ascii_whitespace() {
                return candidate;
            }
            candidate += 1;
        }
        candidate
    }

    /// Finds the next byte start while preserving a matching per-byte prefix.
    ///
    /// # Parameters
    /// - `text`: Text being decoded.
    /// - `index`: Byte index where the next byte may begin.
    ///
    /// # Returns
    /// The current index when a configured per-byte prefix matches, otherwise
    /// the first non-ignored-whitespace index. A structural prefix takes
    /// precedence over whitespace skipping.
    #[must_use]
    #[inline]
    fn next_byte_start(&self, text: &str, mut index: usize) -> usize {
        let prefix = self.config.byte_prefix.as_deref().filter(|prefix| !prefix.is_empty());
        while index < text.len() {
            if prefix.is_some_and(|prefix| self.starts_with_prefix(&text[index..], prefix)) {
                return index;
            }
            if !self.config.ignore_ascii_whitespace || !text.as_bytes()[index].is_ascii_whitespace() {
                return index;
            }
            index += 1;
        }
        index
    }

    /// Decodes unprefixed input characters into bytes.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    /// - `index`: Byte index where parsing should start.
    /// - `output`: Existing buffer to which decoded bytes are appended; an
    ///   error may leave bytes appended before the failure.
    ///
    /// # Returns
    /// `Ok(())` when all bytes are decoded.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::InvalidLength`] when the normalized digit
    /// count is odd, or [`MiscCodecError::InvalidDigit`] for unsupported
    /// characters.
    fn decode_unprefixed(&self, text: &str, mut index: usize, output: &mut Vec<u8>) -> MiscCodecResult<()> {
        let mut pending = None;
        let mut digit_count = 0usize;
        while index < text.len() {
            let rest = &text[index..];
            let ch = rest.chars().next().expect("index is below text length");
            if self.config.ignore_ascii_whitespace && ch.is_ascii_whitespace() {
                index += ch.len_utf8();
                continue;
            }
            if hex_value(ch).is_some() {
                digit_count += 1;
                if let Some(high_char) = pending.take() {
                    output.push(decode_hex_pair(high_char, ch));
                } else {
                    pending = Some(ch);
                }
                index += ch.len_utf8();
                continue;
            }
            return Err(invalid_hex_digit(index, ch));
        }
        if !digit_count.is_multiple_of(2) {
            return Err(invalid_hex_length(digit_count));
        }
        Ok(())
    }

    /// Decodes byte-prefixed input characters into bytes.
    ///
    /// # Parameters
    /// - `text`: Text to decode.
    /// - `prefix`: Required prefix before each byte.
    /// - `index`: Byte index where parsing should start.
    /// - `output`: Existing buffer to which decoded bytes are appended; an
    ///   error may leave bytes appended before the failure.
    ///
    /// # Returns
    /// `Ok(())` when all bytes are decoded.
    ///
    /// # Errors
    /// Returns [`MiscCodecError::MissingPrefix`] when a byte prefix is missing,
    /// [`MiscCodecError::InvalidInput`] when a prefix is not followed by a
    /// complete byte, or [`MiscCodecError::InvalidDigit`] for unsupported
    /// characters.
    fn decode_byte_prefixed(
        &self,
        text: &str,
        prefix: &str,
        mut index: usize,
        output: &mut Vec<u8>,
    ) -> MiscCodecResult<()> {
        let mut digit_count = 0usize;
        while index < text.len() {
            index = self.next_byte_start(text, index);
            if index >= text.len() {
                break;
            }
            let rest = &text[index..];
            if !self.starts_with_prefix(rest, prefix) {
                return Err(MiscCodecError::MissingPrefix {
                    prefix: prefix.to_owned(),
                });
            }
            index += prefix.len();

            let mut pair_count = 0;
            let mut pair = [(0usize, '\0'); 2];
            while pair_count < 2 && index < text.len() {
                let rest = &text[index..];
                let ch = rest.chars().next().expect("index is below text length");
                if self.config.ignore_ascii_whitespace && ch.is_ascii_whitespace() {
                    index += ch.len_utf8();
                    continue;
                }
                if hex_value(ch).is_some() {
                    pair[pair_count] = (index, ch);
                    index += ch.len_utf8();
                    pair_count += 1;
                    digit_count += 1;
                    continue;
                }
                return Err(invalid_hex_digit(index, ch));
            }
            if pair_count != 2 {
                return Err(invalid_hex_input("byte prefix must be followed by two hex digits"));
            }
            output.push(decode_hex_pair(pair[0].1, pair[1].1));
        }
        if !digit_count.is_multiple_of(2) {
            return Err(invalid_hex_length(digit_count));
        }
        Ok(())
    }

    /// Skips ignored ASCII whitespace.
    ///
    /// # Parameters
    /// - `text`: Text being decoded.
    /// - `index`: Current byte index.
    ///
    /// # Returns
    /// The next byte index that should be parsed.
    #[must_use]
    #[inline]
    fn skip_ignored(&self, text: &str, mut index: usize) -> usize {
        while index < text.len() {
            let byte = text.as_bytes()[index];
            if self.config.ignore_ascii_whitespace && byte.is_ascii_whitespace() {
                index += 1;
                continue;
            }
            return index;
        }
        index
    }

    /// Skips ignored leading ASCII whitespace.
    ///
    /// # Parameters
    /// - `text`: Text being decoded.
    /// - `index`: Current byte index.
    ///
    /// # Returns
    /// The next byte index after ignored ASCII whitespace.
    #[must_use]
    #[inline]
    fn skip_ascii_whitespace(&self, text: &str, mut index: usize) -> usize {
        while self.config.ignore_ascii_whitespace && index < text.len() {
            if !text.as_bytes()[index].is_ascii_whitespace() {
                return index;
            }
            index += 1;
        }
        index
    }

    /// Tests whether `text` starts with a configured prefix.
    ///
    /// # Parameters
    /// - `text`: Text slice to inspect.
    /// - `prefix`: Configured prefix.
    ///
    /// # Returns
    /// `true` when `text` starts with `prefix`, honoring the configured
    /// ASCII case sensitivity for decoding prefixes.
    #[must_use]
    #[inline]
    fn starts_with_prefix(&self, text: &str, prefix: &str) -> bool {
        if !self.config.ignore_prefix_case {
            return text.starts_with(prefix);
        }
        let Some(candidate) = text.get(..prefix.len()) else {
            return false;
        };
        candidate.eq_ignore_ascii_case(prefix)
    }
}

impl Default for HexCodec {
    /// Creates a lowercase codec without prefix or separators.
    ///
    /// # Returns
    /// A codec configured with lowercase digits and no formatting tokens.
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl ValueEncoder<[u8]> for HexCodec {
    /// Error type used by the encoder contract; hexadecimal encoding itself
    /// has no failure cases.
    type Error = MiscCodecError;
    /// Complete hexadecimal representation of the supplied byte slice.
    type Output = String;

    /// Encodes the supplied bytes as lowercase or configured-case hexadecimal
    /// text, including the codec's configured prefixes and separators.
    ///
    /// # Parameters
    /// - `input`: Byte slice to encode.
    ///
    /// # Returns
    /// The complete encoded hexadecimal string.
    ///
    /// # Errors
    /// This implementation always succeeds and returns `Ok`.
    #[inline]
    fn encode(&mut self, input: &[u8]) -> Result<Self::Output, Self::Error> {
        Ok(HexCodec::encode(self, input))
    }
}

impl ValueDecoder<str> for HexCodec {
    /// Error type returned when the input violates the configured hex syntax.
    type Error = MiscCodecError;
    /// Decoded bytes, in the order represented by the input text.
    type Output = Vec<u8>;

    /// Decodes hexadecimal text according to this codec's configured prefix,
    /// separator, and whitespace rules.
    ///
    /// # Parameters
    /// - `input`: Hexadecimal text to decode.
    ///
    /// # Returns
    /// The decoded bytes when the input is valid.
    ///
    /// # Errors
    /// Returns the parsing error when the input is malformed or violates the
    /// configured formatting rules.
    #[inline]
    fn decode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
        HexCodec::decode(self, input)
    }
}

/// Converts one hex digit to its value.
///
/// # Parameters
/// - `ch`: Character to inspect.
///
/// # Returns
/// Nibble value, or `None` when `ch` is not a hex digit.
#[must_use]
#[inline]
pub(crate) fn hex_value(ch: char) -> Option<u8> {
    match ch {
        '0'..='9' => Some(ch as u8 - b'0'),
        'a'..='f' => Some(ch as u8 - b'a' + 10),
        'A'..='F' => Some(ch as u8 - b'A' + 10),
        _ => None,
    }
}

/// Builds an invalid hexadecimal digit error.
///
/// # Parameters
/// - `index`: Byte index of the invalid character in the original input.
/// - `character`: Invalid character.
///
/// # Returns
/// A radix-16 digit error.
pub(crate) fn invalid_hex_digit(index: usize, character: char) -> MiscCodecError {
    MiscCodecError::InvalidDigit {
        radix: 16,
        index,
        character,
    }
}

/// Builds an invalid hexadecimal length error.
///
/// # Parameters
/// - `actual`: Number of normalized hexadecimal digits.
///
/// # Returns
/// An invalid length error describing the even-digit requirement.
fn invalid_hex_length(actual: usize) -> MiscCodecError {
    MiscCodecError::InvalidLength {
        context: "hex digits",
        expected: "an even number of digits".to_owned(),
        actual,
    }
}

/// Builds an invalid hexadecimal input error.
///
/// # Parameters
/// - `reason`: Human-readable reason the input was rejected.
///
/// # Returns
/// An invalid input error for the hexadecimal codec.
fn invalid_hex_input(reason: &str) -> MiscCodecError {
    MiscCodecError::InvalidInput {
        codec: "hex",
        reason: reason.to_owned(),
    }
}

/// Reads one required hexadecimal digit at a byte boundary.
///
/// # Parameters
/// - `text`: Text being decoded.
/// - `index`: Byte index where the digit is expected.
///
/// # Returns
/// Original digit index, digit character, and the next byte index.
///
/// # Errors
/// Returns [`MiscCodecError::InvalidInput`] when input ends before the digit,
/// or [`MiscCodecError::InvalidDigit`] when the next character is not hex.
#[inline]
fn read_required_hex_digit(text: &str, index: usize) -> MiscCodecResult<(usize, char, usize)> {
    let rest = &text[index..];
    let Some(character) = rest.chars().next() else {
        return Err(invalid_hex_input("expected a hexadecimal digit"));
    };
    if hex_value(character).is_none() {
        return Err(invalid_hex_digit(index, character));
    }
    Ok((index, character, index + character.len_utf8()))
}

/// Decodes two hexadecimal characters into one byte.
///
/// # Parameters
/// - `high_char`: High-nibble character.
/// - `low_char`: Low-nibble character.
///
/// # Returns
/// The decoded byte.
///
/// The callers validate both characters before constructing the pair.
#[must_use]
#[inline]
fn decode_hex_pair(high_char: char, low_char: char) -> u8 {
    let high = hex_value(high_char).expect("validated hexadecimal digit");
    let low = hex_value(low_char).expect("validated hexadecimal digit");
    (high << 4) | low
}

/// Appends one encoded byte to `output`.
///
/// # Parameters
/// - `byte`: Byte to encode.
/// - `uppercase`: Whether to use uppercase digits.
/// - `output`: Destination string.
#[inline]
fn push_hex_byte(byte: u8, uppercase: bool, output: &mut String) {
    output.push(hex_digit(byte >> 4, uppercase));
    output.push(hex_digit(byte & 0x0f, uppercase));
}

/// Converts one nibble to a hexadecimal digit.
///
/// # Parameters
/// - `value`: Nibble value.
/// - `uppercase`: Whether to use uppercase digits.
///
/// # Returns
/// Hexadecimal digit. Values above `0x0f` are masked to their low nibble.
#[must_use]
#[inline]
pub(crate) fn hex_digit(value: u8, uppercase: bool) -> char {
    let digits = if uppercase {
        &UPPER_HEX_DIGITS
    } else {
        &LOWER_HEX_DIGITS
    };
    digits[(value & 0x0f) as usize]
}