add a_strncpy functions

This commit is contained in:
Julien Danjou 2007-09-24 16:42:04 +02:00
parent 894b341feb
commit df75e01ce0
2 changed files with 33 additions and 1 deletions

26
util.c
View file

@ -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(<tt>n-1</tt>, \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;
}

8
util.h
View file

@ -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);