multi_base/base.rs
1// SPDX-License-Identifier: MIT
2
3use crate::impls::*;
4
5#[cfg(not(feature = "std"))]
6use alloc::{string::String, vec::Vec};
7
8/// Generates the `Base` enum and its implementation with encode/decode methods.
9///
10/// This macro creates a comprehensive base encoding enum with:
11/// - Enum variants for each base type with documentation
12/// - `from_code()` method to convert character codes to base types
13/// - `code()` method to get the character code for a base
14/// - `encode()` method to encode bytes to a base string
15/// - `decode()` method to decode base strings back to bytes
16///
17/// # Macro Hygiene
18///
19/// This macro uses `$crate::` prefixes to ensure proper hygiene when invoked
20/// from other modules or crates.
21///
22/// # Parameters
23///
24/// The macro accepts a comma-separated list of base definitions in the form:
25/// ```text
26/// #[doc = "Documentation"] 'code' => VariantName,
27/// ```
28///
29/// Where:
30/// - `#[doc = "..."]` - Documentation attribute for the enum variant
31/// - `'code'` - The single character or emoji that identifies this base encoding
32/// - `VariantName` - The PascalCase name for the enum variant
33///
34/// # Generated Code
35///
36/// For each base definition, the macro generates:
37/// - An enum variant in the `Base` enum
38/// - A match arm in `from_code()` that maps the character code to the variant
39/// - A match arm in `code()` that returns the character code
40/// - A match arm in `encode()` that delegates to the base's encode function
41/// - A match arm in `decode()` that delegates to the base's decode function
42///
43/// # Example
44///
45/// ```ignore
46/// build_base_enum! {
47/// /// Base64 encoding
48/// 'm' => Base64,
49/// /// Base58 Bitcoin encoding
50/// 'z' => Base58Btc,
51/// }
52/// ```
53///
54/// This generates a `Base` enum with `Base64` and `Base58Btc` variants,
55/// and implements all required methods.
56///
57/// # Error Handling
58///
59/// The `from_code()` method returns `Result<Base>` and will return
60/// `Error::UnknownBase` if given an unrecognized character code.
61macro_rules! build_base_enum {
62 ( $(#[$attr:meta] $code:expr => $base:ident,)* ) => {
63 /// List of types currently supported in the multibase spec.
64 ///
65 /// Not all base types are supported by this library.
66 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
67 pub enum Base {
68 $( #[$attr] $base, )*
69 }
70
71 impl Base {
72 /// Convert a character code to the matching base algorithm.
73 ///
74 /// Returns `Error::UnknownBase` if the code doesn't match any supported base.
75 pub fn from_code(code: char) -> $crate::error::Result<Self> {
76 match code {
77 $( $code => Ok(Self::$base), )*
78 _ => Err($crate::error::Error::UnknownBase { code }),
79 }
80 }
81
82 /// Get the character code corresponding to the base algorithm.
83 ///
84 /// Each base encoding has a unique single-character (or emoji) prefix
85 /// that identifies it in multibase strings.
86 pub fn code(&self) -> char {
87 match self {
88 $( Self::$base => $code, )*
89 }
90 }
91
92 /// Encode the given byte slice to a base string (without prefix).
93 ///
94 /// This method returns only the encoded data, without the base code prefix.
95 /// Use the public `encode()` function to get the full multibase string.
96 pub fn encode<I: AsRef<[u8]>>(&self, input: I) -> String {
97 match self {
98 $( Self::$base => $crate::impls::$base::encode(input), )*
99 }
100 }
101
102 /// Decode the base string (without prefix) back to bytes.
103 ///
104 /// The `strict` parameter controls whether to accept case-insensitive
105 /// input for applicable bases.
106 ///
107 /// # Parameters
108 ///
109 /// * `input` - The encoded string (without the multibase prefix)
110 /// * `strict` - If true, enforce strict decoding rules (case-sensitive, etc.)
111 ///
112 /// # Errors
113 ///
114 /// Returns an error if the input contains invalid characters for this base
115 /// or if the input is malformed.
116 pub fn decode<I: AsRef<str>>(&self, input: I, strict: bool) -> $crate::error::Result<Vec<u8>> {
117 match self {
118 $( Self::$base => $crate::impls::$base::decode(input, strict), )*
119 }
120 }
121
122 pub(crate) fn decode_into<I: AsRef<str>>(&self, input: I, strict: bool, buffer: &mut Vec<u8>) -> $crate::error::Result<()> {
123 match self {
124 $( Self::$base => $crate::impls::$base::decode_into(input, strict, buffer), )*
125 }
126 }
127 }
128 }
129}
130
131build_base_enum! {
132 /// 8-bit binary (encoder and decoder keeps data unmodified).
133 '\x00' => Identity,
134 /// Base2 (alphabet: 01).
135 '0' => Base2,
136 /// Base8 (alphabet: 01234567).
137 '7' => Base8,
138 /// Base10 (alphabet: 0123456789).
139 '9' => Base10,
140 /// Base16 lower hexadecimal (alphabet: 0123456789abcdef).
141 'f' => Base16Lower,
142 /// Base16 upper hexadecimal (alphabet: 0123456789ABCDEF).
143 'F' => Base16Upper,
144 /// Base32, rfc4648 no padding (alphabet: abcdefghijklmnopqrstuvwxyz234567).
145 'b' => Base32Lower,
146 /// Base32, rfc4648 no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
147 'B' => Base32Upper,
148 /// Base32, rfc4648 with padding (alphabet: abcdefghijklmnopqrstuvwxyz234567).
149 'c' => Base32PadLower,
150 /// Base32, rfc4648 with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
151 'C' => Base32PadUpper,
152 /// Base32hex, rfc4648 no padding (alphabet: 0123456789abcdefghijklmnopqrstuv).
153 'v' => Base32HexLower,
154 /// Base32hex, rfc4648 no padding (alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUV).
155 'V' => Base32HexUpper,
156 /// Base32hex, rfc4648 with padding (alphabet: 0123456789abcdefghijklmnopqrstuv).
157 't' => Base32HexPadLower,
158 /// Base32hex, rfc4648 with padding (alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUV).
159 'T' => Base32HexPadUpper,
160 /// z-base-32 (used by Tahoe-LAFS) (alphabet: ybndrfg8ejkmcpqxot1uwisza345h769).
161 'h' => Base32Z,
162 /// Base36, [0-9a-z] no padding (alphabet: 0123456789abcdefghijklmnopqrstuvwxyz).
163 'k' => Base36Lower,
164 /// Base36, [0-9A-Z] no padding (alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ).
165 'K' => Base36Upper,
166 /// Base58 flicker (alphabet: 123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ).
167 'Z' => Base58Flickr,
168 /// Base58 bitcoin (alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz).
169 'z' => Base58Btc,
170 /// Base64, rfc4648 no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/).
171 'm' => Base64,
172 /// Base64, rfc4648 with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/).
173 'M' => Base64Pad,
174 /// Base64 url, rfc4648 no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_).
175 'u' => Base64Url,
176 /// Base64 url, rfc4648 with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_).
177 'U' => Base64UrlPad,
178 /// Base256Emoji (alphabet: ๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ)
179 '๐' => Base256Emoji,
180}