summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEdward Thomson <ethomson@edwardthomson.com>2020-02-26 09:54:18 +0000
committerEdward Thomson <ethomson@edwardthomson.com>2020-06-05 07:14:25 +0100
commit5da8ab9d81713163e8f93c160d0007311a1d1973 (patch)
treeefdd4eba379fd6e38a4f8dcc547a78a085635a5c
parentd296f2970d2358e7117a91e273d1b0fe66012d9e (diff)
downloadlibgit2-5da8ab9d81713163e8f93c160d0007311a1d1973.tar.gz
util: provide helper function to copy strings
Provide a helper function to copy a number of strings from the source to the target.
-rw-r--r--src/util/util.c37
-rw-r--r--src/util/util.h22
2 files changed, 59 insertions, 0 deletions
diff --git a/src/util/util.c b/src/util/util.c
index e37f26fcb..f4a6709e5 100644
--- a/src/util/util.c
+++ b/src/util/util.c
@@ -21,6 +21,43 @@
# include <Shlwapi.h>
#endif
+void git_strings_free_deep(char **strings, size_t n)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++)
+ git__free(strings[i]);
+
+ git__free(strings);
+}
+
+int git_strings_copy_deep(char **tgt, char *const *const src, size_t n)
+{
+ size_t i;
+
+ assert(tgt && src);
+
+ if (!n) {
+ *tgt = NULL;
+ return 0;
+ }
+
+ *tgt = git__calloc(n, sizeof(char *));
+ GIT_ERROR_CHECK_ALLOC(tgt);
+
+ for (i = 0; i < n; i++) {
+ if (!src[i])
+ continue;
+
+ if (!(tgt[i] = git__strdup(src[i]))) {
+ git_strings_free_deep(tgt, n);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
int git__strntol64(int64_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
const char *p;
diff --git a/src/util/util.h b/src/util/util.h
index cdfc9c239..aa4123bf2 100644
--- a/src/util/util.h
+++ b/src/util/util.h
@@ -13,6 +13,8 @@
# include <ctype.h>
#endif
+#include "git2/strarray.h"
+
#include "buffer.h"
#include "strnlen.h"
#include "thread-utils.h"
@@ -334,6 +336,26 @@ extern int git__utf8_iterate(const uint8_t *str, int str_len, int32_t *dst);
*/
extern size_t git__utf8_valid_buf_length(const uint8_t *str, size_t str_len);
+/**
+ * Free the given array and the strings contained therein.
+ *
+ * @param strings The string array to free
+ * @param n The number of strings to free
+ */
+extern void git_strings_free_deep(char **strings, size_t n);
+
+/**
+ * Copy the strings from one array to another. The target array will be
+ * created and the strings will be duplicated into it. Any NULL pointers
+ * in the source will be preserved.
+ *
+ * @param tgt The destination string array
+ * @param src The source string array
+ * @param n The number of strings to copy
+ */
+extern int git_strings_copy_deep(
+ char **tgt, char *const *const src, size_t n);
+
/*
* Safely zero-out memory, making sure that the compiler
* doesn't optimize away the operation.