aboutsummaryrefslogtreecommitdiffstats
path: root/libar2_encode_base64.c
blob: 857b3e8ff46fc9a7b5a00284c3556fe3ce6a5fe0 (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include "common.h"


#define ALPHABET "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
static char lut[256] = ALPHABET ALPHABET ALPHABET ALPHABET;

#define O1(I1, I2, I3) ((I1) >> 2)
#define O2(I1, I2, I3) (((I1) << 4) | ((I2) >> 4))
#define O3(I1, I2, I3) (((I2) << 2) | ((I3) >> 6))
#define O4(I1, I2, I3) (I3)


size_t
libar2_encode_base64(char *buf, const void *data_, size_t len)
{
	const unsigned char *data = data_;
	size_t q, r, i;

	q = len / 3;
	r = len % 3;

	if (buf) {
		for (i = 0; i < q; i++, data += 3) {
			*buf++ = lut[O1(data[0], data[1], data[2]) & 255];
	                *buf++ = lut[O2(data[0], data[1], data[2]) & 255];
			*buf++ = lut[O3(data[0], data[1], data[2]) & 255];
	                *buf++ = lut[O4(data[0], data[1], data[2]) & 255];
		}
		if (r == 1) {
			*buf++ = lut[O1(data[0], 0, 0) & 255];
	                *buf++ = lut[O2(data[0], 0, 0) & 255];
		} else if (r == 2) {
			*buf++ = lut[O1(data[0], data[1], 0) & 255];
	                *buf++ = lut[O2(data[0], data[1], 0) & 255];
			*buf++ = lut[O3(data[0], data[1], 0) & 255];
		}
		*buf = '\0';
	}

	return (q * 4) + r + !!r + 1;
}