]>
Commit | Line | Data |
---|---|---|
4237caa2 MT |
1 | /*############################################################################# |
2 | # # | |
3 | # IPFire.org - A linux based firewall # | |
4 | # Copyright (C) 2023 IPFire Network Development Team # | |
5 | # # | |
6 | # This program is free software: you can redistribute it and/or modify # | |
7 | # it under the terms of the GNU General Public License as published by # | |
8 | # the Free Software Foundation, either version 3 of the License, or # | |
9 | # (at your option) any later version. # | |
10 | # # | |
11 | # This program is distributed in the hope that it will be useful, # | |
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # | |
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # | |
14 | # GNU General Public License for more details. # | |
15 | # # | |
16 | # You should have received a copy of the GNU General Public License # | |
17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. # | |
18 | # # | |
19 | #############################################################################*/ | |
20 | ||
21 | #ifndef NETWORKD_STRING_H | |
22 | #define NETWORKD_STRING_H | |
23 | ||
24 | #include <stdarg.h> | |
25 | ||
26 | static inline int __nw_string_vformat(char* s, const size_t length, | |
27 | const char* format, va_list args) { | |
28 | // Write string to buffer | |
29 | const ssize_t required = vsnprintf(s, length, format, args); | |
30 | ||
31 | // Catch any errors | |
32 | if (required < 0) | |
33 | return 1; | |
34 | ||
35 | // Check if the entire string could be written | |
36 | if ((size_t)required >= length) { | |
37 | errno = ENOMEM; | |
38 | return 1; | |
39 | } | |
40 | ||
41 | // Success | |
42 | return 0; | |
43 | } | |
44 | ||
45 | #define nw_string_format(s, format, ...) \ | |
46 | __nw_string_format(s, sizeof(s), format, __VA_ARGS__) | |
47 | ||
48 | static inline int __nw_string_format(char* s, const size_t length, | |
49 | const char* format, ...) { | |
50 | va_list args; | |
51 | int r; | |
52 | ||
53 | // Call __nw_string_vformat | |
54 | va_start(args, format); | |
55 | r = __nw_string_vformat(s, length, format, args); | |
56 | va_end(args); | |
57 | ||
58 | return r; | |
59 | } | |
60 | ||
61 | #define nw_string_set(s, value) __nw_string_set(s, sizeof(s), value) | |
62 | ||
63 | static inline int __nw_string_set(char* s, const size_t length, const char* value) { | |
64 | // If value is NULL, we will overwrite the buffer with just zeros | |
65 | if (!value) { | |
66 | for (unsigned int i = 0; i < length; i++) | |
67 | s[i] = '\0'; | |
68 | ||
69 | return 0; | |
70 | } | |
71 | ||
72 | // Otherwise just copy | |
73 | return __nw_string_format(s, length, "%s", value); | |
74 | } | |
75 | ||
76 | #endif /* NETWORKD_STRING_H */ |