]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
include/strutils: add strrealloc()
authorKarel Zak <kzak@redhat.com>
Wed, 26 Jun 2019 14:47:24 +0000 (16:47 +0200)
committerKarel Zak <kzak@redhat.com>
Tue, 8 Oct 2019 11:11:53 +0000 (13:11 +0200)
include/strutils.h

index d1f3da1b65f77159cf84ae2ddca0c74ff502d52c..963e3d6f4c3a1cf6605c0e2fd028b4daab35a4db 100644 (file)
@@ -93,6 +93,37 @@ static inline char *mem2strcpy(char *dest, const void *src, size_t n, size_t nma
        return dest;
 }
 
+/* Reallocate @str according to @newstr and copy @newstr to @str; returns new @str */
+static inline char * __attribute__((warn_unused_result))
+strrealloc(char *str, const char *newstr)
+{
+       size_t nsz, osz;
+
+       if (!str)
+               return newstr ? strdup(newstr) : NULL;
+       if (!newstr) {
+               free(str);
+               goto nothing;
+       }
+
+       osz = strlen(str);
+       nsz = strlen(newstr);
+
+       if (nsz > osz) {
+               char *tmp = realloc(str, nsz + 1);
+               if (!tmp)
+                       goto nothing;
+               str = tmp;
+       }
+
+       memcpy(str, newstr, nsz + 1);
+       return str;
+
+nothing:
+       free(str);
+       return NULL;
+}
+
 static inline int strdup_to_offset(void *stru, size_t offset, const char *str)
 {
        char *n = NULL;