-
Notifications
You must be signed in to change notification settings - Fork 1
/
netw.c
55 lines (46 loc) · 861 Bytes
/
netw.c
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
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "netw.h"
#include <stdlib.h>
static bool
is_unreserved(char x)
{
// clang-format off
return (x >= 'A' && x <= 'Z')
|| (x >= 'a' && x <= 'z')
|| (x >= '0' && x <= '9')
|| x == '-'
|| x == '_'
|| x == '.'
|| x == '~';
// clang-format on
}
char *
netw_percent_encode(char const *input, size_t len, size_t *out_len)
{
size_t nlen = 0;
for (size_t i = 0; i < len; ++i)
{
nlen += is_unreserved(input[i]) ? 1 : 3;
}
char const nibbles[] = "0123456789ABCDEF";
char *output = malloc(nlen + 1); // NUL terminate
char *o = output;
for (size_t i = 0; i < len; ++i)
{
if (is_unreserved(input[i]))
{
*(o++) = input[i];
}
else
{
*(o++) = '%';
*(o++) = nibbles[(input[i] >> 4) & 0xf];
*(o++) = nibbles[input[i] & 0xf];
}
}
*o = '\0';
if (out_len)
{
*out_len = (size_t)(o - output);
}
return output;
}