Skip to main content

qubit_codec_misc/
base64_error_kind.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//! Structured Base64 dependency error categories.
9
10use ::base64::DecodeError;
11
12/// Structured category for an error reported by the Base64 dependency.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Base64ErrorKind {
15    /// A byte outside the configured alphabet was encountered.
16    InvalidByte,
17    /// The number of Base64 symbols is invalid.
18    InvalidLength,
19    /// The final symbol contains bits that would be discarded.
20    InvalidLastSymbol,
21    /// Padding is absent, unexpected, or malformed for the configured engine.
22    InvalidPadding,
23}
24
25impl Base64ErrorKind {
26    /// Classifies a Base64 dependency error without discarding its source.
27    #[inline]
28    pub(crate) const fn from_decode_error(error: &DecodeError) -> Self {
29        match error {
30            DecodeError::InvalidByte(_, _) => Self::InvalidByte,
31            DecodeError::InvalidLength(_) => Self::InvalidLength,
32            DecodeError::InvalidLastSymbol { .. } => Self::InvalidLastSymbol,
33            DecodeError::InvalidPadding => Self::InvalidPadding,
34        }
35    }
36
37    /// Returns the input offset carried by this Base64 error, when available.
38    #[inline]
39    pub(crate) const fn input_index(error: &DecodeError) -> Option<usize> {
40        match error {
41            DecodeError::InvalidByte(index, _) | DecodeError::InvalidLastSymbol { offset: index, .. } => Some(*index),
42            DecodeError::InvalidLength(_) | DecodeError::InvalidPadding => None,
43        }
44    }
45
46    /// Returns the invalid symbol carried by this Base64 error, when present.
47    #[inline]
48    pub(crate) const fn symbol(error: &DecodeError) -> Option<u8> {
49        match error {
50            DecodeError::InvalidByte(_, symbol) | DecodeError::InvalidLastSymbol { symbol, .. } => Some(*symbol),
51            DecodeError::InvalidLength(_) | DecodeError::InvalidPadding => None,
52        }
53    }
54
55    /// Returns the invalid input length carried by this Base64 error, when
56    /// present.
57    #[inline]
58    pub(crate) const fn input_length(error: &DecodeError) -> Option<usize> {
59        match error {
60            DecodeError::InvalidLength(length) => Some(*length),
61            DecodeError::InvalidByte(_, _) | DecodeError::InvalidLastSymbol { .. } | DecodeError::InvalidPadding => {
62                None
63            }
64        }
65    }
66}