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
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(feature = "unstable", feature(arm_target_feature))]
#![deny(
missing_debug_implementations,
missing_docs,
clippy::all,
clippy::cargo,
clippy::missing_inline_in_public_items
)]
#![warn(clippy::todo)]
#[cfg(feature = "alloc")]
extern crate alloc;
pub use simd_abstraction::tools::OutBuf;
mod error;
pub use self::error::Error;
pub(crate) use self::error::ERROR;
mod utils;
#[cfg(test)]
mod tests;
pub mod fallback;
#[macro_use]
mod generic;
mod polyfill;
pub mod arch;
mod auto;
mod ext;
#[derive(Debug)]
enum Base64Kind {
Standard,
UrlSafe,
}
#[derive(Debug)]
pub struct Base64 {
kind: Base64Kind,
padding: bool,
}
impl Base64 {
const PAD: u8 = b'=';
pub const STANDARD: Self = Self {
kind: Base64Kind::Standard,
padding: true,
};
pub const STANDARD_NO_PAD: Self = Self {
kind: Base64Kind::Standard,
padding: false,
};
pub const URL_SAFE: Self = Self {
kind: Base64Kind::UrlSafe,
padding: true,
};
pub const URL_SAFE_NO_PAD: Self = Self {
kind: Base64Kind::UrlSafe,
padding: false,
};
#[inline(always)]
const unsafe fn encoded_length_unchecked(n: usize, padding: bool) -> usize {
let extra = n % 3;
if extra == 0 {
n / 3 * 4
} else if padding {
n / 3 * 4 + 4
} else {
n / 3 * 4 + extra + 1
}
}
#[inline(always)]
unsafe fn decoded_length_unchecked(src: &[u8], padding: bool) -> Result<(usize, usize), Error> {
let n = {
let len = src.len();
if padding {
if len % 4 != 0 {
return Err(ERROR);
}
let last1 = *src.get_unchecked(len - 1);
let last2 = *src.get_unchecked(len - 2);
let count = (last1 == Base64::PAD) as usize + (last2 == Base64::PAD) as usize;
len - count
} else {
len
}
};
let m = match n % 4 {
0 => n / 4 * 3,
1 => return Err(ERROR),
2 => n / 4 * 3 + 1,
3 => n / 4 * 3 + 2,
_ => core::hint::unreachable_unchecked(),
};
Ok((n, m))
}
#[inline]
pub const fn encoded_length(&self, n: usize) -> usize {
assert!(n <= (isize::MAX as usize));
unsafe { Self::encoded_length_unchecked(n, self.padding) }
}
#[inline]
pub const fn charset(&self) -> &[u8; 64] {
match self.kind {
Base64Kind::Standard => fallback::STANDARD_CHARSET,
Base64Kind::UrlSafe => fallback::URL_SAFE_CHARSET,
}
}
}