-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_uriencode.c
68 lines (62 loc) · 1.63 KB
/
ft_uriencode.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
56
57
58
59
60
61
62
63
64
65
66
67
68
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_uriencode.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asarandi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/27 15:46:21 by asarandi #+# #+# */
/* Updated: 2017/09/28 13:32:39 by asarandi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_ue_unreserved(int c)
{
if (ft_isalnum(c))
return (1);
if ((c == '-') || (c == '_'))
return (1);
if ((c == '.') || (c == '~'))
return (1);
return (0);
}
static int ft_ue_length(char *s)
{
int i;
int r;
i = 0;
r = 0;
while (s[i])
{
if (ft_ue_unreserved(s[i]))
r++;
i++;
}
return (((ft_strlen(s) - r) * 3) + r);
}
char *ft_uriencode(char *s)
{
const char *hex = "0123456789ABCDEF";
char *mem;
int i;
int k;
mem = malloc((ft_ue_length(s) + 1) * sizeof(char));
if (!mem)
return (NULL);
i = 0;
k = 0;
while (s[i])
{
if (ft_ue_unreserved(s[i]))
mem[k++] = s[i];
else
{
mem[k++] = '%';
mem[k++] = hex[s[i] / 16];
mem[k++] = hex[s[i] % 16];
}
i++;
}
mem[k] = 0;
return (mem);
}