forked from michaelforney/st
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase64dec.c
42 lines (40 loc) · 860 Bytes
/
base64dec.c
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
/*taken from libulz with permission*/
const char base64_tbl[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
inline int chrpos(int c) {
int i = 0;
for(;i<64;i++) if(base64_tbl[i] == c) return i;
return -1;
}
size_t base64dec(void* dst, const char* src, size_t dst_len) {
const char* s = src;
unsigned char *d = dst;
size_t l = dst_len, o = 0;
int n = 0, cnt = 0, skip = 0;
if(l) for(;;) {
int p;
if(*s == '=') {
skip++;
if(skip > 2) return 0;
p = 0;
} else if (!*s) {
if(cnt % 4 != 0 || !l) return 0;
*d++ = 0;
return o;
} else if(skip) {
return 0;
} else if((p = chrpos(*s)) == -1) return 0;
n = (n << 6) | p;
cnt++;
if(cnt % 4 == 0) {
if(l < 3) return 0;
*d++ = n >> 16;
*d++ = n >> 8 & 0xff;
*d++ = n & 0xff;
l -= 3;
o += 3-skip;
n = 0;
}
s++;
}
return 0;
}