diff options
author | Karel Zak | 2018-10-03 17:03:11 +0200 |
---|---|---|
committer | Karel Zak | 2018-10-03 17:03:11 +0200 |
commit | a338eb4a467e136970c6fc6891f10d80535f8765 (patch) | |
tree | 675d7de2daec789e9dea02a42c55f50aa3b54c3a /include | |
parent | include/ttyutils: define values if missing. (diff) | |
download | kernel-qcow2-util-linux-a338eb4a467e136970c6fc6891f10d80535f8765.tar.gz kernel-qcow2-util-linux-a338eb4a467e136970c6fc6891f10d80535f8765.tar.xz kernel-qcow2-util-linux-a338eb4a467e136970c6fc6891f10d80535f8765.zip |
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 <kzak@redhat.com>
Diffstat (limited to 'include')
-rw-r--r-- | include/strutils.h | 28 |
1 files changed, 28 insertions, 0 deletions
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; |