aboutsummaryrefslogtreecommitdiff
path: root/tools/server/base64.c
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-06-20 20:10:56 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-06-21 05:57:19 +0200
commit6b969d25ce136eaf695222bd1a10bff1ecac0220 (patch)
treec23afb50c28b9deaddae5c6526a74ee11cf2d865 /tools/server/base64.c
parentd4bdb8dae753462f621507d5fc3582e0e53da35c (diff)
downloadffwd-6b969d25ce136eaf695222bd1a10bff1ecac0220.tar.gz
ffwd-6b969d25ce136eaf695222bd1a10bff1ecac0220.zip
all: split Makefile and reorg library/tools
Diffstat (limited to 'tools/server/base64.c')
-rw-r--r--tools/server/base64.c47
1 files changed, 47 insertions, 0 deletions
diff --git a/tools/server/base64.c b/tools/server/base64.c
new file mode 100644
index 0000000..87351d2
--- /dev/null
+++ b/tools/server/base64.c
@@ -0,0 +1,47 @@
+#include "base64.h"
+#include "util.h"
+
+#include <stdint.h>
+
+char *base64_encode(const unsigned char *src, size_t n) {
+ static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ size_t max_groups = (SIZE_MAX - 1) / 4;
+ if (n > max_groups * 3)
+ die_oom();
+
+ size_t out_len = ((n + 2) / 3) * 4;
+ char *out = xmalloc(out_len + 1);
+ const unsigned char *p = src;
+ const unsigned char *end = src + (n / 3) * 3;
+ char *q = out;
+
+ while (p < end) {
+ uint32_t v = ((uint32_t)p[0] << 16) | ((uint32_t)p[1] << 8) | (uint32_t)p[2];
+ q[0] = tbl[(v >> 18) & 63];
+ q[1] = tbl[(v >> 12) & 63];
+ q[2] = tbl[(v >> 6) & 63];
+ q[3] = tbl[v & 63];
+ p += 3;
+ q += 4;
+ }
+
+ size_t rem = n - (size_t)(p - src);
+ if (rem == 1) {
+ uint32_t v = (uint32_t)p[0] << 16;
+ q[0] = tbl[(v >> 18) & 63];
+ q[1] = tbl[(v >> 12) & 63];
+ q[2] = '=';
+ q[3] = '=';
+ q += 4;
+ } else if (rem == 2) {
+ uint32_t v = ((uint32_t)p[0] << 16) | ((uint32_t)p[1] << 8);
+ q[0] = tbl[(v >> 18) & 63];
+ q[1] = tbl[(v >> 12) & 63];
+ q[2] = tbl[(v >> 6) & 63];
+ q[3] = '=';
+ q += 4;
+ }
+
+ *q = '\0';
+ return out;
+}