base_x/
alphabet.rs

1#[cfg(not(feature = "std"))]
2use alloc::{string::String, vec::Vec};
3use DecodeError;
4
5use decoder::*;
6use encoder;
7
8pub trait Alphabet {
9    fn encode(self, input: &[u8]) -> String;
10
11    fn decode(self, input: &str) -> Result<Vec<u8>, DecodeError>;
12}
13
14impl<'a> Alphabet for &[u8] {
15    #[inline(always)]
16    fn encode(self, input: &[u8]) -> String {
17        if !self.is_ascii() {
18            panic!("Alphabet must be ASCII");
19        }
20
21        let mut out = encoder::encode(self, input);
22        out.reverse();
23        unsafe { String::from_utf8_unchecked(out) }
24    }
25
26    #[inline(always)]
27    fn decode(self, input: &str) -> Result<Vec<u8>, DecodeError> {
28        U8Decoder::new(self).decode(input)
29    }
30}
31
32impl<'a> Alphabet for &str {
33    #[inline(always)]
34    fn encode(self, input: &[u8]) -> String {
35        if self.is_ascii() {
36            let mut out = encoder::encode(self.as_bytes(), input);
37            out.reverse();
38            unsafe { String::from_utf8_unchecked(out) }
39        } else {
40            let alphabet: Vec<char> = self.chars().collect();
41            let out = encoder::encode(&alphabet, input);
42            out.iter().rev().collect()
43        }
44    }
45
46    #[inline(always)]
47    fn decode(self, input: &str) -> Result<Vec<u8>, DecodeError> {
48        if self.is_ascii() {
49            U8Decoder::new(self.as_bytes()).decode(input)
50        } else {
51            let alphabet: Vec<char> = self.chars().collect();
52            CharDecoder(&alphabet).decode(input)
53        }
54    }
55}