This source file includes following definitions.
- memdup
- strtobool
- strlcpy
- skip_spaces
- strim
- strreplace
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <linux/string.h>
20 #include <linux/ctype.h>
21 #include <linux/compiler.h>
22
23
24
25
26
27
28
29 void *memdup(const void *src, size_t len)
30 {
31 void *p = malloc(len);
32
33 if (p)
34 memcpy(p, src, len);
35
36 return p;
37 }
38
39
40
41
42
43
44
45
46
47
48 int strtobool(const char *s, bool *res)
49 {
50 if (!s)
51 return -EINVAL;
52
53 switch (s[0]) {
54 case 'y':
55 case 'Y':
56 case '1':
57 *res = true;
58 return 0;
59 case 'n':
60 case 'N':
61 case '0':
62 *res = false;
63 return 0;
64 case 'o':
65 case 'O':
66 switch (s[1]) {
67 case 'n':
68 case 'N':
69 *res = true;
70 return 0;
71 case 'f':
72 case 'F':
73 *res = false;
74 return 0;
75 default:
76 break;
77 }
78 default:
79 break;
80 }
81
82 return -EINVAL;
83 }
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99 #ifdef __clang__
100 #pragma clang diagnostic push
101 #pragma clang diagnostic ignored "-Wignored-attributes"
102 #endif
103 size_t __weak strlcpy(char *dest, const char *src, size_t size)
104 {
105 size_t ret = strlen(src);
106
107 if (size) {
108 size_t len = (ret >= size) ? size - 1 : ret;
109 memcpy(dest, src, len);
110 dest[len] = '\0';
111 }
112 return ret;
113 }
114 #ifdef __clang__
115 #pragma clang diagnostic pop
116 #endif
117
118
119
120
121
122
123
124 char *skip_spaces(const char *str)
125 {
126 while (isspace(*str))
127 ++str;
128 return (char *)str;
129 }
130
131
132
133
134
135
136
137
138
139 char *strim(char *s)
140 {
141 size_t size;
142 char *end;
143
144 size = strlen(s);
145 if (!size)
146 return s;
147
148 end = s + size - 1;
149 while (end >= s && isspace(*end))
150 end--;
151 *(end + 1) = '\0';
152
153 return skip_spaces(s);
154 }
155
156
157
158
159
160
161
162
163
164 char *strreplace(char *s, char old, char new)
165 {
166 for (; *s; ++s)
167 if (*s == old)
168 *s = new;
169 return s;
170 }