Port: Add compat for strnlen and strndup
[babeltrace.git] / include / babeltrace / compat / string.h
index 5d6a0632d5b3ef67e6db510eb99e3ae9ab161bb0..7a574e679d207f4a03549e9f2ddce1751c2ae210 100644 (file)
@@ -24,6 +24,7 @@
  */
 
 #include <string.h>
  */
 
 #include <string.h>
+#include <stdlib.h>
 
 #if !defined(__linux__) || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
 
 
 #if !defined(__linux__) || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
 
@@ -51,4 +52,65 @@ int compat_strerror_r(int errnum, char *buf, size_t buflen)
 
 #endif
 
 
 #endif
 
+#ifdef HAVE_STRNLEN
+static inline
+size_t bt_strnlen(const char *str, size_t max)
+{
+       return strnlen(str, max);
+}
+#else
+static inline
+size_t bt_strnlen(const char *str, size_t max)
+{
+       size_t ret;
+       const char *end;
+
+       end = memchr(str, 0, max);
+
+       if (end) {
+               ret = (size_t) (end - str);
+       } else {
+               ret = max;
+       }
+
+       return ret;
+}
+#endif /* HAVE_STRNLEN */
+
+#ifdef HAVE_STRNDUP
+static inline
+char *bt_strndup(const char *s, size_t n)
+{
+       return strndup(s, n);
+}
+#else
+static inline
+char *bt_strndup(const char *s, size_t n)
+{
+       char *ret;
+       size_t navail;
+
+       if (!s) {
+               ret = NULL;
+               goto end;
+       }
+
+       /* min() */
+       navail = strlen(s) + 1;
+       if ((n + 1) < navail) {
+               navail = n + 1;
+       }
+
+       ret = malloc(navail);
+       if (!ret) {
+               goto end;
+       }
+
+       memcpy(ret, s, navail);
+       ret[navail - 1] = '\0';
+end:
+       return ret;
+}
+#endif /* HAVE_STRNDUP */
+
 #endif /* _BABELTRACE_COMPAT_STRING_H */
 #endif /* _BABELTRACE_COMPAT_STRING_H */
This page took 0.023508 seconds and 4 git commands to generate.