-
Notifications
You must be signed in to change notification settings - Fork 0
/
strutils.c
92 lines (75 loc) · 2.28 KB
/
strutils.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
arfhttpd: Yet another HTTP server
Copyright (C) 2023 arf20 (Ángel Ruiz Fernandez)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
strutils.c: string utilities
*/
#include "strutils.h"
#include <string.h>
#include <stdio.h>
size_t /* from BSD */
strlcat(char *dst, const char *src, size_t dstsize) {
int d_len, s_len, offset, src_index;
/* obtain initial sizes */
d_len = strlen(dst);
s_len = strlen(src);
/* get the end of dst */
offset = d_len;
/* append src */
src_index = 0;
while(*(src+src_index) != '\0')
{
*(dst + offset) = *(src + src_index);
offset++;
src_index++;
/* don't copy more than dstsize characters
minus one */
if(offset == dstsize - 1)
break;
}
/* always cap the string! */
*(dst + offset) = '\0';
return d_len + s_len;
}
void
strsub(char *dest, size_t destsize, const char *src, size_t n) {
int i = 0;
for (i = 0; i < n && i < destsize && src[i]; i++)
dest[i] = src[i];
dest[i] = '\0';
}
char *
stralloccpy(const char *start, size_t length) {
if (!start) return NULL;
char *str = malloc(length + 1);
strncpy(str, start, length);
str[length] = '\0';
return str;
}
char *
human_size(int isize, char *buf, size_t buflen) {
int i = 0;
float size = isize;
const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
while (size > 1024.0f) {
size /= 1024.0f;
i++;
}
snprintf(buf, buflen, "%.*f %s", i, size, units[i]);
return buf;
}
const char *
strnchr(const char *str, size_t n, char chr) {
for (int i = 0; i < n; i++)
if (str[i] == chr) return str + i;
return NULL;
}