Skip to content

Commit 86c58a5

Browse files
ethomsonEdward Thomson
authored andcommitted
str: add hexadigit encoding to strings
1 parent 3c53796 commit 86c58a5

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/str.c

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,32 @@ int git_str_puts(git_str *buf, const char *string)
217217
return git_str_put(buf, string, strlen(string));
218218
}
219219

220+
static char hex_encode[] = "0123456789abcdef";
221+
222+
int git_str_encode_hexstr(git_str *str, const char *data, size_t len)
223+
{
224+
size_t new_size, i;
225+
char *s;
226+
227+
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&new_size, len, 2);
228+
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
229+
230+
if (git_str_grow_by(str, new_size) < 0)
231+
return -1;
232+
233+
s = str->ptr + str->size;
234+
235+
for (i = 0; i < len; i++) {
236+
*s++ = hex_encode[(data[i] & 0xf0) >> 4];
237+
*s++ = hex_encode[(data[i] & 0x0f)];
238+
}
239+
240+
str->size += (len * 2);
241+
str->ptr[str->size] = '\0';
242+
243+
return 0;
244+
}
245+
220246
static const char base64_encode[] =
221247
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
222248

src/str.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,9 @@ int git_str_cmp(const git_str *a, const git_str *b);
217217
int git_str_quote(git_str *str);
218218
int git_str_unquote(git_str *str);
219219

220+
/* Write data as a hex string */
221+
int git_str_encode_hexstr(git_str *str, const char *data, size_t len);
222+
220223
/* Write data as base64 encoded in string buffer */
221224
int git_str_encode_base64(git_str *str, const char *data, size_t len);
222225
/* Decode the given bas64 and write the result to the string buffer */

0 commit comments

Comments
 (0)