Eina: add eina_strndup() API as inlined function
authorVincent Torri <vincent.torri@gmail.com>
Tue, 30 Apr 2019 15:37:54 +0000 (15:37 +0000)
committerHermet Park <hermetpark@gmail.com>
Wed, 8 May 2019 04:25:02 +0000 (13:25 +0900)
this add strndup implementation that does not seg fault when string is NULL.
This also implements strndup on Windows.

Reviewed-by: Cedric BAIL <cedric.bail@free.fr>
Differential Revision: https://phab.enlightenment.org/D8790

src/lib/eina/eina_inline_str.x
src/lib/eina/eina_str.h

index 3b75591..d61eda5 100644 (file)
@@ -82,6 +82,38 @@ eina_strdup(const char *str)
 }
 
 /**
+ * @brief strndup function which takes @c NULL without crashing
+ * @param str The string to copy
+ * @param n The maximum number of char to copy
+ * @return the copied string, must be freed
+ * @note this also implements strndup() on Windows
+ * @since 1.23
+ */
+static inline char *
+eina_strndup(const char *str, size_t n)
+{
+#ifdef _WIN32
+   char *ret;
+   size_t slen;
+
+   if (!str)
+     return NULL;
+
+   slen = strnlen(str, n);
+   ret = (char *)malloc(slen + 1); /* cast for C++ code */
+   if (!ret)
+     return NULL;
+   if (slen > 0)
+     memcpy(ret, str, slen);
+   ret[slen] = '\0';
+
+   return ret;
+#else
+   return str ? strndup(str, n) : NULL;
+#endif
+}
+
+/**
  * @brief streq function which takes @c NULL without crashing
  * @param a string a
  * @param b string b
index e8bf685..c7d7e4e 100644 (file)
@@ -382,6 +382,16 @@ EAPI unsigned char *eina_memdup(unsigned char *mem, size_t size, Eina_Bool termi
  */
 EAPI char *eina_strftime(const char *format, const struct tm *tm);
 
+static inline size_t eina_strlen_bounded(const char *str, size_t maxlen);
+
+static inline size_t eina_str_join(char *dst, size_t size, char sep, const char *a, const char *b);
+
+static inline char *eina_strdup(const char *str);
+
+static inline char *eina_strndup(const char *str, size_t n);
+
+static inline Eina_Bool eina_streq(const char *a, const char *b);
+
 #include "eina_inline_str.x"
 
 /**