]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
include/c: add str2memcpy() and mem2strcpy()
authorKarel Zak <kzak@redhat.com>
Wed, 3 Oct 2018 15:03:11 +0000 (17:03 +0200)
committerKarel Zak <kzak@redhat.com>
Wed, 3 Oct 2018 15:03:11 +0000 (17:03 +0200)
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>
include/strutils.h

index f5979d936ee039c0bcd9cd2eeb12b08df586dcbf..0c46798821471300fb1212fbcd6597893cf54155 100644 (file)
@@ -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;