summaryrefslogtreecommitdiffstats
path: root/src/utils/include/strutils.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/include/strutils.h')
-rw-r--r--src/utils/include/strutils.h38
1 files changed, 36 insertions, 2 deletions
diff --git a/src/utils/include/strutils.h b/src/utils/include/strutils.h
index 4b3182f..09cc35e 100644
--- a/src/utils/include/strutils.h
+++ b/src/utils/include/strutils.h
@@ -9,6 +9,8 @@
#include <stdio.h>
#include <errno.h>
+#include "c.h"
+
/* initialize a custom exit code for all *_or_err functions */
extern void strutils_set_exitcode(int exit_code);
@@ -61,8 +63,13 @@ extern char *strnchr(const char *s, size_t maxlen, int c);
/* caller guarantees n > 0 */
static inline void xstrncpy(char *dest, const char *src, size_t n)
{
- strncpy(dest, src, n-1);
- dest[n-1] = 0;
+ size_t len = src ? strlen(src) : 0;
+
+ if (!len)
+ return;
+ len = min(len, n - 1);
+ memcpy(dest, src, len);
+ dest[len] = 0;
}
/* This is like strncpy(), but based on memcpy(), so compilers and static
@@ -303,6 +310,33 @@ static inline size_t ltrim_whitespace(unsigned char *str)
return len;
}
+/* Removes left-hand, right-hand and repeating whitespaces.
+ */
+static inline size_t normalize_whitespace(unsigned char *str)
+{
+ size_t i, x, sz = strlen((char *) str);
+ int nsp = 0, intext = 0;
+
+ if (!sz)
+ return 0;
+
+ for (i = 0, x = 0; i < sz; ) {
+ if (isspace(str[i]))
+ nsp++;
+ else
+ nsp = 0, intext = 1;
+
+ if (nsp > 1 || (nsp && !intext))
+ i++;
+ else
+ str[x++] = str[i++];
+ }
+ if (nsp) /* tailing space */
+ x--;
+ str[x] = '\0';
+ return x;
+}
+
static inline void strrep(char *s, int find, int replace)
{
while (s && *s && (s = strchr(s, find)) != NULL)