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
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Encoding {
Base64(B64CharSet),
Base32(B32CharSet),
Hex(HexCharSet),
}
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum B64CharSet {
Standard,
UrlSafe,
}
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum HexCharSet {
Lowercase,
Uppercase,
}
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum B32CharSet {
Standard,
}
pub(crate) struct CharSetLookup<const CHARS: usize> {
pub(crate) into_enc: [u8; CHARS],
pub(crate) from_enc: [u8; 256],
}
macro_rules! declare_assoc_consts {
(
char_set = $char_set:ident,
characters = $chars:expr,
$(
($variant:ident, $assoc:ident, $value:expr)
)*
) => {
impl $char_set {
pub(crate) const fn lookup(self) -> &'static CharSetLookup<$chars> {
match self {
$(
Self::$variant => <CharSetLookup<$chars>>::$assoc,
)*
}
}
}
impl CharSetLookup<$chars> {
$(
pub(crate) const $assoc: &'static Self = &$value;
)*
}
};
}
declare_assoc_consts! {
char_set = B64CharSet,
characters = 64,
(Standard, STANDARD, {
let mut out = [0u8; 64];
let mut out_i = 0usize;
for_range_inc!{c in b'A', b'Z' => write_into!{out, out_i, c} }
for_range_inc!{c in b'a', b'z' => write_into!{out, out_i, c} }
for_range_inc!{c in b'0', b'9' => write_into!{out, out_i, c} }
write_into!{out, out_i, b'+'}
write_into!{out, out_i, b'/'}
Self::new(out)
})
(UrlSafe, URL_SAFE, {
let mut out = Self::STANDARD.into_enc;
out[62] = b'-';
out[63] = b'_';
Self::new(out)
})
}
declare_assoc_consts! {
char_set = B32CharSet,
characters = 32,
(Standard, STANDARD, {
let mut out = [0u8; 32];
let mut out_i = 0usize;
for_range_inc!{c in b'A', b'Z' => write_into!{out, out_i, c} }
for_range_inc!{c in b'2', b'7' => write_into!{out, out_i, c} }
Self::new(out)
})
}
pub(crate) const INVALID_ENC: u8 = u8::MAX;
impl<const N: usize> CharSetLookup<N> {
const fn new(into_enc: [u8; N]) -> Self {
let mut from_enc = [INVALID_ENC; 256];
for_range! {i in 0usize..N =>
from_enc[into_enc[i] as usize] = i as u8;
}
Self { from_enc, into_enc }
}
}