GCC Code Coverage Report


Directory: src/
File: src/base64.c
Date: 2024-04-25 03:45:42
Exec Total Coverage
Lines: 18 27 66.7%
Branches: 3 12 25.0%

Line Branch Exec Source
1 /*
2 * Copyright (c) 2023 Egor Tensin <egor@tensin.name>
3 * This file is part of the "cimple" project.
4 * For details, see https://github.com/egor-tensin/cimple.
5 * Distributed under the MIT License.
6 */
7
8 #include "base64.h"
9 #include "log.h"
10
11 #include <sodium.h>
12
13 #include <stddef.h>
14 #include <stdlib.h>
15 #include <string.h>
16
17 static const int base64_variant = sodium_base64_VARIANT_ORIGINAL;
18
19 9180 int base64_encode(const unsigned char *src, size_t src_len, char **_dst)
20 {
21 9180 const size_t dst_len = sodium_base64_encoded_len(src_len, base64_variant);
22
23 9180 char *dst = calloc(dst_len, 1);
24
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 9180 times.
9180 if (!dst) {
25 log_errno("calloc");
26 return -1;
27 }
28
29 9180 sodium_bin2base64(dst, dst_len, src, src_len, base64_variant);
30
31 9180 *_dst = dst;
32 9180 return 0;
33 }
34
35 9180 int base64_decode(const char *src, unsigned char **_dst, size_t *_dst_len)
36 {
37 9180 const size_t src_len = strlen(src);
38 9180 const size_t dst_max_len = src_len / 4 * 3;
39 9180 size_t dst_len = 0;
40
41 9180 unsigned char *dst = calloc(dst_max_len, 1);
42
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 9180 times.
9180 if (!dst) {
43 log_errno("calloc");
44 return -1;
45 }
46
47 int ret =
48 9180 sodium_base642bin(dst, dst_max_len, src, src_len, NULL, &dst_len, NULL, base64_variant);
49
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 9180 times.
9180 if (ret < 0) {
50 log_err("Couldn't parse base64-encoded string\n");
51 goto free;
52 }
53
54 9180 *_dst = dst;
55 9180 *_dst_len = dst_len;
56 9180 return ret;
57
58 free:
59 free(dst);
60
61 return ret;
62 }
63