From df75e01ce00c822b112e2491559b638c6dceb628 Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Mon, 24 Sep 2007 16:42:04 +0200 Subject: [PATCH] add a_strncpy functions --- util.c | 26 ++++++++++++++++++++++++++ util.h | 8 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/util.c b/util.c index 520e05871..bbb1cd36b 100644 --- a/util.c +++ b/util.c @@ -142,3 +142,29 @@ compute_new_value_from_arg(const char *arg, double current_value) return current_value; } + +/** \brief safe limited strcpy. + * + * Copies at most min(n-1, \c l) characters from \c src into \c dst, + * always adding a final \c \\0 in \c dst. + * + * \param[in] dst destination buffer. + * \param[in] n size of the buffer. Negative sizes are allowed. + * \param[in] src source string. + * \param[in] l maximum number of chars to copy. + * + * \return minimum of \c src \e length and \c l. +*/ +ssize_t a_strncpy(char *dst, ssize_t n, const char *src, ssize_t l) +{ + ssize_t len = MIN(a_strlen(src), l); + + if (n > 0) + { + ssize_t dlen = MIN(n - 1, len); + memcpy(dst, src, dlen); + dst[dlen] = '\0'; + } + + return len; +} diff --git a/util.h b/util.h index ea0b3750a..a9fcf537b 100644 --- a/util.h +++ b/util.h @@ -30,6 +30,11 @@ /** \brief replace \c NULL strings with emtpy strings */ #define NONULL(x) (x ? x : "") +#undef MAX +#undef MIN +#define MAX(a,b) ((a) < (b) ? (b) : (a)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + #define ssizeof(foo) (ssize_t)sizeof(foo) #define countof(foo) (ssizeof(foo) / ssizeof(foo[0])) @@ -104,7 +109,6 @@ static inline ssize_t a_strlen(const char *s) return s ? strlen(s) : 0; } - /** \brief \c NULL resistant strdup. * * the a_strdup() function returns a pointer to a new string, which is a @@ -132,6 +136,8 @@ static inline int a_strcmp(const char *a, const char *b) return strcmp(NONULL(a), NONULL(b)); } +ssize_t a_strncpy(char *dst, ssize_t n, const char *src, ssize_t l) __attribute__((nonnull(1))); + void die(const char *, ...) __attribute__ ((noreturn)) __attribute__ ((format(printf, 1, 2))); void eprint(const char *, ...) __attribute__ ((noreturn)) __attribute__ ((format(printf, 1, 2))); Bool xgettextprop(Display *, Window, Atom, char *, unsigned int);