From a338eb4a467e136970c6fc6891f10d80535f8765 Mon Sep 17 00:00:00 2001 From: Karel Zak Date: Wed, 3 Oct 2018 17:03:11 +0200 Subject: include/c: add str2memcpy() and mem2strcpy() str2memcpy() - copy zero terminated string to optionally terminated buffer mem2strcpy() - copy from buffer to zero terminated string Signed-off-by: Karel Zak --- include/strutils.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'include/strutils.h') diff --git a/include/strutils.h b/include/strutils.h index f5979d936..0c4679882 100644 --- a/include/strutils.h +++ b/include/strutils.h @@ -65,6 +65,34 @@ static inline void xstrncpy(char *dest, const char *src, size_t n) dest[n-1] = 0; } +/* This is like strncpy(), but based on memcpy(), so compilers and static + * analyzers do not complain when sizeof(destination) is the same as 'n' and + * result is not terminated by zero. + * + * Use this function to copy string to logs with fixed sizes (wtmp/utmp. ...) + * where string terminator is optional. + */ +static inline void *str2memcpy(void *dest, const char *src, size_t n) +{ + size_t bytes = strlen(src) + 1; + + if (bytes > n) + bytes = n; + + memcpy(dest, src, bytes); + return dest; +} + +static inline char *mem2strcpy(char *dest, const void *src, size_t n, size_t nmax) +{ + if (n + 1 > nmax) + n = nmax - 1; + + memcpy(dest, src, n); + dest[nmax-1] = '\0'; + return dest; +} + static inline int strdup_to_offset(void *stru, size_t offset, const char *str) { char *n = NULL; -- cgit v1.2.3-55-g7522