From 946ba59190a6cef1ead1d64149b2a7baf686fac3 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sun, 10 May 2009 15:41:18 +0200 Subject: [PATCH] [MINOR] standard: provide a new 'my_strndup' function This function is only offered by GNU extensions and is sometimes useful during configuration parsing. --- include/common/standard.h | 3 +++ src/standard.c | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/include/common/standard.h b/include/common/standard.h index 6e7e9634a9..0bc28aafc4 100644 --- a/include/common/standard.h +++ b/include/common/standard.h @@ -302,4 +302,7 @@ static inline unsigned int mul32hi(unsigned int a, unsigned int b) return ((unsigned long long)a * b) >> 32; } +/* copies at most characters from and always terminates with '\0' */ +char *my_strndup(const char *src, int n); + #endif /* _COMMON_STANDARD_H */ diff --git a/src/standard.c b/src/standard.c index 906f2a730f..de5b664432 100644 --- a/src/standard.c +++ b/src/standard.c @@ -654,6 +654,23 @@ const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags) return NULL; } +/* copies at most characters from and always terminates with '\0' */ +char *my_strndup(const char *src, int n) +{ + int len = 0; + char *ret; + + while (len < n && src[len]) + len++; + + ret = (char *)malloc(len + 1); + if (!ret) + return ret; + memcpy(ret, src, len); + ret[len] = '\0'; + return ret; +} + /* * Local variables: * c-indent-level: 8