added latency tool
[tridge/junkcode.git] / base64.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <stdlib.h>
5
6 /*
7   encode as base64
8   caller frees
9 */
10 static char *base64_encode(const char *buf, int len)
11 {
12         const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
13         int bit_offset, byte_offset, idx, i;
14         const unsigned char *d = (const unsigned char *)buf;
15         int bytes = (len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
16         char *out;
17
18         out = calloc(1, bytes+pad_bytes+1);
19         if (!out) return NULL;
20
21         for (i=0;i<bytes;i++) {
22                 byte_offset = (i*6)/8;
23                 bit_offset = (i*6)%8;
24                 if (bit_offset < 3) {
25                         idx = (d[byte_offset] >> (2-bit_offset)) & 0x3F;
26                 } else {
27                         idx = (d[byte_offset] << (bit_offset-2)) & 0x3F;
28                         if (byte_offset+1 < len) {
29                                 idx |= (d[byte_offset+1] >> (8-(bit_offset-2)));
30                         }
31                 }
32                 out[i] = b64[idx];
33         }
34
35         for (;i<bytes+pad_bytes;i++)
36                 out[i] = '=';
37         out[i] = 0;
38
39         return out;
40 }
41
42
43 static int load_stdin(char **s)
44 {
45         char buf[1024];
46         int length = 0;
47
48         *s = NULL;
49
50         while (1) {
51                 int n = read(0, buf, sizeof(buf));
52                 if (n == -1 && errno == EINTR) continue;
53                 if (n <= 0) break;
54
55                 (*s) = realloc((*s), length + n + 1);
56                 if (!(*s)) return 0;
57
58                 memcpy((*s)+length, buf, n);
59                 length += n;
60         }
61
62         (*s)[length] = 0;
63         
64         return length;
65 }
66
67 int main(int argc, char *argv[])
68 {
69         char *s;
70         int n;
71
72         n = load_stdin(&s);
73
74         printf("%s\n", base64_encode(s, n));
75         return 0;
76 }