multi-base 1.0.2

multibase in rust
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
// SPDX-License-Identifier: MIT

use crate::encoding;
use crate::error::Result;
#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
#[cfg(feature = "std")]
use std::{collections::HashMap, sync::OnceLock};

/// Generates `BaseCodec` implementations for data-encoding-based encodings.
///
/// This macro creates type wrappers and `BaseCodec` trait implementations for
/// base encodings that use the `data-encoding` crate. It handles both strict
/// and permissive decoding modes.
///
/// # Macro Hygiene
///
/// Uses `$crate::` prefixes to ensure proper hygiene when invoked from
/// different modules or crates.
///
/// # Parameters
///
/// The macro accepts a comma-separated list of encoding definitions:
/// ```text
/// #[doc = "Documentation"] TypeName, ENCODING_CONSTANT, PERMISSIVE_ENCODING;
/// ```
///
/// Where:
/// - `#[doc = "..."]` - Documentation for the generated type
/// - `TypeName` - `PascalCase` name for the struct (e.g., `Base64`, `Base32Lower`)
/// - `ENCODING_CONSTANT` - Strict encoding spec from `data-encoding` crate
/// - `PERMISSIVE_ENCODING` - Permissive encoding spec (case-insensitive, etc.)
///
/// # Generated Code
///
/// For each encoding definition, generates:
/// 1. A zero-sized struct type
/// 2. `BaseCodec` implementation with `encode()` and `decode()` methods
/// 3. Strict/permissive decoding logic based on the `strict` parameter
///
/// # Example
///
/// ```ignore
/// derive_base_encoding! {
///     /// Base64 encoding
///     Base64, encoding::BASE64_NOPAD, encoding::BASE64_NOPAD_PERMISSIVE;
/// }
/// ```
///
/// # Strict vs Permissive Mode
///
/// - **Strict mode**: Uses the exact encoding specification (case-sensitive)
/// - **Permissive mode**: Accepts variations like mixed case where applicable
///
/// # Error Handling
///
/// Decoding errors from `data-encoding` are automatically converted to the
/// crate's `Error` type via the `?` operator.
macro_rules! derive_base_encoding {
    ( $(#[$doc:meta] $type:ident, $encoding:expr, $permissive:expr;)* ) => {
        $(
            #[$doc]
            #[derive(PartialEq, Eq, Clone, Copy, Debug)]
            pub struct $type;

            impl BaseCodec for $type {
                #[inline]
                fn encode<I: AsRef<[u8]>>(input: I) -> String {
                    $encoding.encode(input.as_ref())
                }

                #[inline]
                fn decode<I: AsRef<str>>(input: I, strict: bool) -> $crate::error::Result<Vec<u8>> {
                    if strict {
                        Ok($encoding.decode(input.as_ref().as_bytes())?)
                    } else {
                        Ok($permissive.decode(input.as_ref().as_bytes())?)
                    }
                }
            }
        )*
    };
}

/// Generates `BaseCodec` implementations for base-x-based encodings.
///
/// This macro creates type wrappers and `BaseCodec` trait implementations for
/// base encodings that use the `base-x` crate (variable-radix encodings like
/// Base10, Base58, etc.). It handles both strict and permissive decoding modes.
///
/// # Macro Hygiene
///
/// Uses `$crate::` prefixes to ensure proper hygiene when invoked from
/// different modules or crates.
///
/// # Parameters
///
/// The macro accepts a comma-separated list of encoding definitions:
/// ```text
/// #[doc = "Documentation"] TypeName, ALPHABET, PERMISSIVE_ALPHABET;
/// ```
///
/// Where:
/// - `#[doc = "..."]` - Documentation for the generated type
/// - `TypeName` - `PascalCase` name for the struct (e.g., `Base58Btc`, `Base10`)
/// - `ALPHABET` - Strict alphabet string for this encoding
/// - `PERMISSIVE_ALPHABET` - Permissive alphabet (may be same as strict)
///
/// # Generated Code
///
/// For each encoding definition, generates:
/// 1. A zero-sized struct type
/// 2. `BaseCodec` implementation with `encode()` and `decode()` methods
/// 3. Strict/permissive decoding logic based on the `strict` parameter
///
/// # Example
///
/// ```ignore
/// derive_base_x! {
///     /// Base58 Bitcoin encoding
///     Base58Btc, encoding::BASE58_BITCOIN, encoding::BASE58_BITCOIN_PERMISSIVE;
/// }
/// ```
///
/// # Difference from `derive_base_encoding`
///
/// This macro uses `base_x::encode/decode` instead of `data-encoding`, which
/// is appropriate for variable-radix encodings where the alphabet defines the base.
///
/// **Why Two Separate Macros?**
///
/// While `derive_base_encoding` and `derive_base_x` appear similar, they use
/// different APIs:
/// - `derive_base_encoding`: Calls methods on `data-encoding` objects
/// - `derive_base_x`: Calls functions from the `base-x` crate
///
/// Keeping them separate maintains clarity and avoids complex conditional logic.
///
/// # Strict vs Permissive Mode
///
/// - **Strict mode**: Uses the exact alphabet
/// - **Permissive mode**: May accept variations (though often identical to strict)
///
/// # Error Handling
///
/// Decoding errors from `base-x` are automatically converted to the
/// crate's `Error` type via the `?` operator.
macro_rules! derive_base_x {
    ( $(#[$doc:meta] $type:ident, $encoding:expr, $permissive:expr;)* ) => {
        $(
            #[$doc]
            #[derive(PartialEq, Eq, Clone, Copy, Debug)]
            pub struct $type;

            impl BaseCodec for $type {
                #[inline]
                fn encode<I: AsRef<[u8]>>(input: I) -> String {
                    base_x::encode($encoding, input.as_ref())
                }

                #[inline]
                fn decode<I: AsRef<str>>(input: I, strict: bool) -> $crate::error::Result<Vec<u8>> {
                    if strict {
                        Ok(base_x::decode($encoding, input.as_ref())?)
                    } else {
                        Ok(base_x::decode($permissive, input.as_ref())?)
                    }
                }
            }
        )*
    };
}

pub trait BaseCodec {
    /// Encode with the given byte slice.
    fn encode<I: AsRef<[u8]>>(input: I) -> String;

    /// Decode with the given string.
    fn decode<I: AsRef<str>>(input: I, strict: bool) -> Result<Vec<u8>>;

    /// Decode into an existing buffer.
    fn decode_into<I: AsRef<str>>(input: I, strict: bool, buffer: &mut Vec<u8>) -> Result<()> {
        let decoded = Self::decode(input, strict)?;
        buffer.clear();
        buffer.extend_from_slice(&decoded);
        Ok(())
    }
}

/// Identity, 8-bit binary (encoder and decoder keeps data unmodified).
///
/// # Encoding Behavior
///
/// When encoding with Identity, the input bytes are interpreted as UTF-8.
/// Invalid UTF-8 sequences are replaced with the Unicode replacement character (U+FFFD).
/// This uses [`String::from_utf8_lossy`] to ensure the operation never panics.
///
/// # Round-Trip Safety (Known Limitation)
///
/// Identity encoding is **not round-trip safe** for arbitrary binary data:
/// `decode(encode(bytes)) != bytes` whenever `bytes` is not valid UTF-8,
/// because the invalid bytes are replaced with U+FFFD on encode and never
/// recovered on decode. Callers that need to preserve exact binary data
/// must use a different base encoding (e.g. Base64) instead of Identity.
///
/// # Security Note
///
/// If you need to preserve exact binary data, consider using a different base encoding
/// like Base64 instead of Identity.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct Identity;

impl BaseCodec for Identity {
    fn encode<I: AsRef<[u8]>>(input: I) -> String {
        // Lossy conversion prevents panics on invalid UTF-8 binary data.
        String::from_utf8_lossy(input.as_ref()).into_owned()
    }

    fn decode<I: AsRef<str>>(input: I, _strict: bool) -> Result<Vec<u8>> {
        Ok(input.as_ref().as_bytes().to_vec())
    }

    fn decode_into<I: AsRef<str>>(input: I, _strict: bool, buffer: &mut Vec<u8>) -> Result<()> {
        buffer.clear();
        buffer.extend_from_slice(input.as_ref().as_bytes());
        Ok(())
    }
}

/// `Base256Emoji` (alphabet: ๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚)
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct Base256Emoji;

const EMOJI_ALPHABET: &str = "๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚";

#[cfg(feature = "std")]
fn emoji_chars() -> &'static [char] {
    static CHARS: OnceLock<Vec<char>> = OnceLock::new();
    CHARS
        .get_or_init(|| EMOJI_ALPHABET.chars().collect())
        .as_slice()
}

#[cfg(feature = "std")]
fn emoji_decode_map() -> &'static HashMap<char, u8> {
    static MAP: OnceLock<HashMap<char, u8>> = OnceLock::new();
    MAP.get_or_init(|| {
        EMOJI_ALPHABET
            .chars()
            .enumerate()
            .map(|(index, c)| (c, u8::try_from(index).expect("emoji alphabet fits in u8")))
            .collect()
    })
}

impl BaseCodec for Base256Emoji {
    fn encode<I: AsRef<[u8]>>(input: I) -> String {
        #[cfg(feature = "std")]
        {
            let chars = emoji_chars();
            input.as_ref().iter().map(|&b| chars[b as usize]).collect()
        }

        #[cfg(not(feature = "std"))]
        {
            let chars: Vec<char> = EMOJI_ALPHABET.chars().collect();
            input.as_ref().iter().map(|&b| chars[b as usize]).collect()
        }
    }

    fn decode<I: AsRef<str>>(input: I, _strict: bool) -> Result<Vec<u8>> {
        #[cfg(feature = "std")]
        {
            let map = emoji_decode_map();
            input
                .as_ref()
                .chars()
                .map(|c| {
                    map.get(&c)
                        .copied()
                        .ok_or(crate::error::Error::Base256EmojiDecode)
                })
                .collect()
        }

        #[cfg(not(feature = "std"))]
        {
            input
                .as_ref()
                .chars()
                .map(|c| {
                    EMOJI_ALPHABET
                        .chars()
                        .position(|a| a == c)
                        .map(|i| i as u8)
                        .ok_or(crate::error::Error::Base256EmojiDecode)
                })
                .collect()
        }
    }

    fn decode_into<I: AsRef<str>>(input: I, _strict: bool, buffer: &mut Vec<u8>) -> Result<()> {
        #[cfg(feature = "std")]
        {
            let map = emoji_decode_map();
            let input = input.as_ref();
            let len = input.chars().count();
            for c in input.chars() {
                if !map.contains_key(&c) {
                    return Err(crate::error::Error::Base256EmojiDecode);
                }
            }

            buffer.clear();
            buffer.reserve(len);
            buffer.extend(input.chars().map(|c| map[&c]));
            Ok(())
        }

        #[cfg(not(feature = "std"))]
        {
            let input = input.as_ref();
            let len = input.chars().count();
            for c in input.chars() {
                if !EMOJI_ALPHABET.chars().any(|a| a == c) {
                    return Err(crate::error::Error::Base256EmojiDecode);
                }
            }

            buffer.clear();
            buffer.reserve(len);
            for c in input.chars() {
                let byte = EMOJI_ALPHABET
                    .chars()
                    .position(|a| a == c)
                    .map(|i| i as u8)
                    .expect("emoji was already validated");
                buffer.push(byte);
            }
            Ok(())
        }
    }
}

derive_base_encoding! {
    /// Base2 (alphabet: 01).
    Base2, encoding::BASE2, encoding::BASE2_PERMISSIVE;
    /// Base8 (alphabet: 01234567).
    Base8, encoding::BASE8, encoding::BASE8_PERMISSIVE;
    /// Base16 lower hexadecimal (alphabet: 0123456789abcdef).
    Base16Lower, encoding::BASE16_LOWER, encoding::BASE16_LOWER_PERMISSIVE;
    /// Base16 upper hexadecimal (alphabet: 0123456789ABCDEF).
    Base16Upper, encoding::BASE16_UPPER, encoding::BASE16_UPPER_PERMISSIVE;
    /// Base32, rfc4648 no padding (alphabet: abcdefghijklmnopqrstuvwxyz234567).
    Base32Lower, encoding::BASE32_NOPAD_LOWER, encoding::BASE32_NOPAD_LOWER_PERMISSIVE;
    /// Base32, rfc4648 no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
    Base32Upper, encoding::BASE32_NOPAD_UPPER, encoding::BASE32_NOPAD_UPPER_PERMISSIVE;
    /// Base32, rfc4648 with padding (alphabet: abcdefghijklmnopqrstuvwxyz234567).
    Base32PadLower, encoding::BASE32_PAD_LOWER, encoding::BASE32_PAD_LOWER_PERMISSIVE;
    /// Base32, rfc4648 with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
    Base32PadUpper, encoding::BASE32_PAD_UPPER, encoding::BASE32_PAD_UPPER_PERMISSIVE;
    /// Base32hex, rfc4648 no padding (alphabet: 0123456789abcdefghijklmnopqrstuv).
    Base32HexLower, encoding::BASE32HEX_NOPAD_LOWER, encoding::BASE32HEX_NOPAD_LOWER_PERMISSIVE;
    /// Base32hex, rfc4648 no padding (alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUV).
    Base32HexUpper, encoding::BASE32HEX_NOPAD_UPPER, encoding::BASE32HEX_NOPAD_UPPER_PERMISSIVE;
    /// Base32hex, rfc4648 with padding (alphabet: 0123456789abcdefghijklmnopqrstuv).
    Base32HexPadLower, encoding::BASE32HEX_PAD_LOWER, encoding::BASE32HEX_PAD_LOWER_PERMISSIVE;
    /// Base32hex, rfc4648 with padding (alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUV).
    Base32HexPadUpper, encoding::BASE32HEX_PAD_UPPER, encoding::BASE32HEX_PAD_UPPER_PERMISSIVE;
    /// z-base-32 (used by Tahoe-LAFS) (alphabet: ybndrfg8ejkmcpqxot1uwisza345h769).
    Base32Z, encoding::BASE32Z, encoding::BASE32Z_PERMISSIVE;
    /// Base64, `rfc4648` no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/).
    Base64, encoding::BASE64_NOPAD, encoding::BASE64_NOPAD_PERMISSIVE;
    /// Base64, `rfc4648` with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/).
    Base64Pad, encoding::BASE64_PAD, encoding::BASE64_PAD_PERMISSIVE;
    /// Base64 url, `rfc4648` no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_).
    Base64Url, encoding::BASE64URL_NOPAD, encoding::BASE64URL_NOPAD_PERMISSIVE;
    /// Base64 url, `rfc4648` with padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_).
    Base64UrlPad, encoding::BASE64URL_PAD, encoding::BASE64URL_PAD_PERMISSIVE;
}

derive_base_x! {
    /// Base10 (alphabet: 0123456789).
    Base10, encoding::BASE10, encoding::BASE10_PERMISSIVE;
    /// Base58 flicker (alphabet: 123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ).
    Base58Flickr, encoding::BASE58_FLICKR, encoding::BASE58_FLICKR_PERMISSIVE;
    /// Base58 bitcoin (alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz).
    Base58Btc, encoding::BASE58_BITCOIN, encoding::BASE58_BITCOIN_PERMISSIVE;
}

/// Base36, [0-9a-z] no padding (alphabet: abcdefghijklmnopqrstuvwxyz0123456789).
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct Base36Lower;

impl BaseCodec for Base36Lower {
    fn encode<I: AsRef<[u8]>>(input: I) -> String {
        base_x::encode(encoding::BASE36_LOWER, input.as_ref())
    }

    fn decode<I: AsRef<str>>(input: I, strict: bool) -> Result<Vec<u8>> {
        if strict {
            Ok(base_x::decode(encoding::BASE36_LOWER, input.as_ref())?)
        } else {
            // The input is case insensitive, hence lowercase it
            let lowercased = input.as_ref().to_ascii_lowercase();
            Ok(base_x::decode(
                encoding::BASE36_LOWER_PERMISSIVE,
                &lowercased,
            )?)
        }
    }
}

/// Base36, [0-9A-Z] no padding (alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789).
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct Base36Upper;

impl BaseCodec for Base36Upper {
    fn encode<I: AsRef<[u8]>>(input: I) -> String {
        base_x::encode(encoding::BASE36_UPPER, input.as_ref())
    }

    fn decode<I: AsRef<str>>(input: I, strict: bool) -> Result<Vec<u8>> {
        if strict {
            Ok(base_x::decode(encoding::BASE36_UPPER, input.as_ref())?)
        } else {
            // The input is case insensitive, hence uppercase it
            let uppercased = input.as_ref().to_ascii_uppercase();
            Ok(base_x::decode(
                encoding::BASE36_UPPER_PERMISSIVE,
                &uppercased,
            )?)
        }
    }
}