dup_crypto/
bases.rs

1//  Copyright (C) 2020 Éloïs SANCHEZ.
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as
5// published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16//! Provide base convertion tools
17
18use thiserror::Error;
19
20/// Base16 conversion tools
21pub mod b16;
22
23/// Base58 conversion tools
24pub mod b58;
25
26/// Base64 conversion tools
27pub mod b64;
28
29/// Errors enumeration for Base 16/58/64 strings convertion.
30#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
31pub enum BaseConversionError {
32    #[error("Data have invalid length : expected {expected:?}, found {found:?}.")]
33    /// Data have invalid length.
34    InvalidLength {
35        /// Expected length
36        expected: usize,
37        /// Actual length
38        found: usize,
39    },
40    #[error("Invalid character '{character:?}' at offset {offset:?}.")]
41    /// Base58/64 have an invalid character.
42    InvalidCharacter {
43        /// Character
44        character: char,
45        /// Offset (=position)
46        offset: usize,
47    },
48    #[error("Invalid base converter length.")]
49    /// Base58/64 have invalid lendth
50    InvalidBaseConverterLength,
51    #[error("Invalid last symbol '{symbol:?}' at offset {offset:?}.")]
52    /// Base64 have invalid last symbol (symbol, offset)
53    InvalidLastSymbol {
54        /// Symbol
55        symbol: u8,
56        /// Offset (=position)
57        offset: usize,
58    },
59    /// Unknown error
60    #[error("Unknown error.")]
61    UnknownError,
62}
63
64impl From<base64::DecodeError> for BaseConversionError {
65    fn from(err: base64::DecodeError) -> Self {
66        match err {
67            base64::DecodeError::InvalidByte(offset, byte) => {
68                BaseConversionError::InvalidCharacter {
69                    character: byte as char,
70                    offset,
71                }
72            }
73            base64::DecodeError::InvalidLength => BaseConversionError::InvalidBaseConverterLength,
74            base64::DecodeError::InvalidLastSymbol(offset, symbol) => {
75                BaseConversionError::InvalidLastSymbol { symbol, offset }
76            }
77        }
78    }
79}