summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEdward Thomson <ethomson@edwardthomson.com>2022-02-07 23:10:38 -0500
committerEdward Thomson <ethomson@github.com>2022-02-09 09:41:22 -0500
commit86c58a5b6f89785fe6982f161e7c1f4075839a73 (patch)
tree8d9e62f2e839cf6128682cb25618d470b178623d
parent3c53796cbe4e8c8425b4b41598913bb5cbc1f5a1 (diff)
downloadlibgit2-86c58a5b6f89785fe6982f161e7c1f4075839a73.tar.gz
str: add hexadigit encoding to strings
-rw-r--r--src/str.c26
-rw-r--r--src/str.h3
2 files changed, 29 insertions, 0 deletions
diff --git a/src/str.c b/src/str.c
index 9d579f144..0d405bfda 100644
--- a/src/str.c
+++ b/src/str.c
@@ -217,6 +217,32 @@ int git_str_puts(git_str *buf, const char *string)
return git_str_put(buf, string, strlen(string));
}
+static char hex_encode[] = "0123456789abcdef";
+
+int git_str_encode_hexstr(git_str *str, const char *data, size_t len)
+{
+ size_t new_size, i;
+ char *s;
+
+ GIT_ERROR_CHECK_ALLOC_MULTIPLY(&new_size, len, 2);
+ GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
+
+ if (git_str_grow_by(str, new_size) < 0)
+ return -1;
+
+ s = str->ptr + str->size;
+
+ for (i = 0; i < len; i++) {
+ *s++ = hex_encode[(data[i] & 0xf0) >> 4];
+ *s++ = hex_encode[(data[i] & 0x0f)];
+ }
+
+ str->size += (len * 2);
+ str->ptr[str->size] = '\0';
+
+ return 0;
+}
+
static const char base64_encode[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
diff --git a/src/str.h b/src/str.h
index af7acc21f..ef769ce2f 100644
--- a/src/str.h
+++ b/src/str.h
@@ -217,6 +217,9 @@ int git_str_cmp(const git_str *a, const git_str *b);
int git_str_quote(git_str *str);
int git_str_unquote(git_str *str);
+/* Write data as a hex string */
+int git_str_encode_hexstr(git_str *str, const char *data, size_t len);
+
/* Write data as base64 encoded in string buffer */
int git_str_encode_base64(git_str *str, const char *data, size_t len);
/* Decode the given bas64 and write the result to the string buffer */