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, _)
42            | DecodeError::InvalidLastSymbol(index, _) => Some(*index),
43            DecodeError::InvalidLength(_) | DecodeError::InvalidPadding => None,
44        }
45    }
46
47    /// Returns the invalid symbol carried by this Base64 error, when present.
48    #[inline]
49    pub(crate) const fn symbol(error: &DecodeError) -> Option<u8> {
50        match error {
51            DecodeError::InvalidByte(_, symbol)
52            | DecodeError::InvalidLastSymbol(_, symbol) => Some(*symbol),
53            DecodeError::InvalidLength(_) | DecodeError::InvalidPadding => None,
54        }
55    }
56
57    /// Returns the invalid input length carried by this Base64 error, when
58    /// present.
59    #[inline]
60    pub(crate) const fn input_length(error: &DecodeError) -> Option<usize> {
61        match error {
62            DecodeError::InvalidLength(length) => Some(*length),
63            DecodeError::InvalidByte(_, _)
64            | DecodeError::InvalidLastSymbol(_, _)
65            | DecodeError::InvalidPadding => None,
66        }
67    }
68}