aboutsummaryrefslogtreecommitdiffstats
path: root/libar2_encode_base64.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2022-01-16 19:58:57 +0100
committerMattias Andrée <maandree@kth.se>2022-01-16 19:58:57 +0100
commit8bdc2e4929068210d523c34c0b171b51ce96057f (patch)
treec77331e77b9777a37716bffb7365c4486a6df9a0 /libar2_encode_base64.c
downloadlibar2-8bdc2e4929068210d523c34c0b171b51ce96057f.tar.gz
libar2-8bdc2e4929068210d523c34c0b171b51ce96057f.tar.bz2
libar2-8bdc2e4929068210d523c34c0b171b51ce96057f.tar.xz
First commit1.0
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'libar2_encode_base64.c')
-rw-r--r--libar2_encode_base64.c42
1 files changed, 42 insertions, 0 deletions
diff --git a/libar2_encode_base64.c b/libar2_encode_base64.c
new file mode 100644
index 0000000..857b3e8
--- /dev/null
+++ b/libar2_encode_base64.c
@@ -0,0 +1,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;
+}