Graphviz 13.0.0~dev.20250402.0402
Loading...
Searching...
No Matches
base64.c
Go to the documentation of this file.
1#include <stddef.h>
2#include <util/alloc.h>
3#include <util/base64.h>
4
5static size_t div_up(size_t dividend, size_t divisor) {
6 return dividend / divisor + (dividend % divisor != 0);
7}
8
9static const char base64_alphabet[] =
10 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
11
12size_t gv_base64_size(size_t source_size) { return div_up(source_size, 3) * 4; }
13
14char *gv_base64(const unsigned char *source, size_t size) {
15 size_t buf_i = 0;
16 char *buf = gv_alloc(gv_base64_size(size) + 1);
17
18 for (size_t data_i = 0; data_i < size; data_i += 3) {
19 unsigned char d0 = source[data_i];
20 int v = (d0 & 0xFC) >> 2; // 1111_1100
21 buf[buf_i++] = base64_alphabet[v];
22
23 unsigned char d1 = data_i + 1 < size ? source[data_i + 1] : 0;
24 v = (d0 & 0x03) << 4 // 0000_0011
25 | (d1 & 0xF0) >> 4; // 1111_0000
26 buf[buf_i++] = base64_alphabet[v];
27 if (size <= data_i + 1) {
28 goto end;
29 }
30
31 unsigned char d2 = data_i + 2 < size ? source[data_i + 2] : 0;
32 v = (d1 & 0x0F) << 2 // 0000_1111
33 | (d2 & 0xC0) >> 6; // 1100_0000
34 buf[buf_i++] = base64_alphabet[v];
35 if (size <= data_i + 2) {
36 goto end;
37 }
38
39 v = d2 & 0x3F; // 0011_1111
40 buf[buf_i++] = base64_alphabet[v];
41 }
42
43end:
44 while (buf_i % 4 != 0) {
45 buf[buf_i++] = base64_alphabet[64];
46 }
47
48 // Write a string terminator. This is not strictly necessary, but is a
49 // backstop against callers who do not use `gv_base64_size` and assume they
50 // can e.g. `fputs` the returned data.
51 buf[buf_i++] = '\0';
52
53 return buf;
54}
Memory allocation wrappers that exit on failure.
static void * gv_alloc(size_t size)
Definition alloc.h:47
char * gv_base64(const unsigned char *source, size_t size)
Definition base64.c:14
size_t gv_base64_size(size_t source_size)
Definition base64.c:12
static size_t div_up(size_t dividend, size_t divisor)
Definition base64.c:5
static const char base64_alphabet[]
Definition base64.c:9
Base64 encoding.