diff th_string.c @ 220:099a1a156fd7

Implement th_strndup_trim() and factorize implementation of th_strdup_trim().
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 15 Feb 2016 10:11:10 +0200
parents 1ee46a95aa8c
children 81b4688f684b
line wrap: on
line diff
--- a/th_string.c	Mon Feb 15 06:05:42 2016 +0200
+++ b/th_string.c	Mon Feb 15 10:11:10 2016 +0200
@@ -53,15 +53,14 @@
  * according to specified flags. See TH_TRIM_* in
  * th_string.h
  */
-char *th_strdup_trim(const char *src, const int flags)
+static inline th_strdup_trim_do(const char src, size_t len, const int flags)
 {
     char *res;
-    size_t start, end, len;
-    if (src == NULL)
+    size_t start, end;
+
+    if (len == 0)
         return NULL;
 
-    len = strlen(src);
-
     // Trim start: find first non-whitespace character
     if (flags & TH_TRIM_START)
         for (start = 0; start < len && th_isspace(src[start]); start++);
@@ -85,6 +84,27 @@
 }
 
 
+char *th_strdup_trim(const char *src, const int flags)
+{
+    if (src == NULL)
+        return NULL;
+
+    return th_strdup_trim_do(src, strlen(src), flags);
+}
+
+
+char *th_strndup_trim(const char *src, const size_t n, const int flags)
+{
+    size_t len;
+    if (src == NULL || n == 0)
+        return NULL;
+
+    for (len = 0; len < n && src[len]; len++);
+
+    return th_strdup_trim_do(src, len, flags);
+}
+
+
 /* Simulate a sprintf() that allocates memory
  */
 char *th_strdup_vprintf(const char *fmt, va_list args)