Port: replace strerror_r() with glib g_strerror()
[babeltrace.git] / include / babeltrace / compat / string.h
index 5d6a0632d5b3ef67e6db510eb99e3ae9ab161bb0..c3325a3b11a6c654f56af4badeb0c1ef3dab23cf 100644 (file)
  */
 
 #include <string.h>
+#include <stdlib.h>
 
-#if !defined(__linux__) || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
-
-/* XSI-compliant strerror_r */
+#ifdef HAVE_STRNLEN
 static inline
-int compat_strerror_r(int errnum, char *buf, size_t buflen)
+size_t bt_strnlen(const char *str, size_t max)
 {
-       return strerror_r(errnum, buf, buflen);
+       return strnlen(str, max);
 }
-
 #else
-
-/* GNU-compliant strerror_r */
 static inline
-int compat_strerror_r(int errnum, char *buf, size_t buflen)
+size_t bt_strnlen(const char *str, size_t max)
 {
-       char *retbuf;
+       size_t ret;
+       const char *end;
+
+       end = memchr(str, 0, max);
 
-       retbuf = strerror_r(errnum, buf, buflen);
-       if (retbuf != buf)
-               strncpy(buf, retbuf, buflen);
-       buf[buflen - 1] = '\0';
-       return 0;
+       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;
 
-#endif
+       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 */
This page took 0.029448 seconds and 4 git commands to generate.