string_util.c: provide fallback strndup() implementation

This patch also adds extern "C" { } wrapper around string_util.h
to allow its usage in C++ code
This commit is contained in:
Denis Krjuchkov 2013-01-11 13:51:39 +06:00
parent 631a268996
commit a98aa66620
4 changed files with 50 additions and 0 deletions

View File

@ -135,6 +135,8 @@ AC_SEARCH_LIBS([gethostbyname], [nsl])
AC_CHECK_FUNCS(pipe2 accept4 eventfd) AC_CHECK_FUNCS(pipe2 accept4 eventfd)
AC_CHECK_FUNCS(strndup)
AC_SEARCH_LIBS([exp], [m],, AC_SEARCH_LIBS([exp], [m],,
[AC_MSG_ERROR([exp() not found])]) [AC_MSG_ERROR([exp() not found])])

View File

@ -21,6 +21,7 @@
#define MPD_OPUS_READER_HXX #define MPD_OPUS_READER_HXX
#include "check.h" #include "check.h"
#include "string_util.h"
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>

View File

@ -20,6 +20,8 @@
#include "config.h" #include "config.h"
#include "string_util.h" #include "string_util.h"
#include <stdlib.h> /* for malloc() */
#include <string.h> /* for strnlen() */
#include <glib.h> #include <glib.h>
#include <assert.h> #include <assert.h>
@ -45,3 +47,22 @@ string_array_contains(const char *const* haystack, const char *needle)
return false; return false;
} }
#if !defined(HAVE_STRNDUP)
char *
strndup(const char *str, size_t n)
{
assert(str != NULL);
size_t len = strnlen(str, n);
char* ret = (char *) malloc(len + 1);
if (ret == NULL)
return NULL;
memcpy(ret, str, len);
ret[len] = '\0';
return ret;
}
#endif

View File

@ -23,6 +23,11 @@
#include "gcc.h" #include "gcc.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/** /**
* Remove the "const" attribute from a string pointer. This is a * Remove the "const" attribute from a string pointer. This is a
@ -78,4 +83,25 @@ strchug_fast(char *p)
bool bool
string_array_contains(const char *const* haystack, const char *needle); string_array_contains(const char *const* haystack, const char *needle);
#if !defined(HAVE_STRNDUP)
/**
* Duplicates the string to a newly allocated buffer
* copying at most n characters.
*
* @param str a string to duplicate
* @param n maximal number of characters to copy
* @return a pointer to the duplicated string,
* or NULL if memory allocation failed.
*/
gcc_malloc
char *
strndup(const char *str, size_t n);
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif #endif