oid: introduce git_oid__is_hexstr Introduce a function that determines whether a given string is a valid object id (40 chars of hexadigits).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
diff --git a/src/oid.h b/src/oid.h
index 84231ff..7a89d21 100644
--- a/src/oid.h
+++ b/src/oid.h
@@ -48,4 +48,16 @@ GIT_INLINE(void) git_oid__cpy_prefix(
out->id[len / 2] &= 0xF0;
}
+GIT_INLINE(bool) git_oid__is_hexstr(const char *str)
+{
+ size_t i;
+
+ for (i = 0; str[i] != '\0'; i++) {
+ if (git__fromhex(str[i]) < 0)
+ return false;
+ }
+
+ return (i == GIT_OID_HEXSZ);
+}
+
#endif
diff --git a/tests/core/oid.c b/tests/core/oid.c
index 7ee6fb6..894fead 100644
--- a/tests/core/oid.c
+++ b/tests/core/oid.c
@@ -1,4 +1,5 @@
#include "clar_libgit2.h"
+#include "oid.h"
static git_oid id;
static git_oid idp;
@@ -68,3 +69,11 @@ void test_core_oid__ncmp(void)
cl_assert(!git_oid_ncmp(&id, &id, 40));
cl_assert(!git_oid_ncmp(&id, &id, 41));
}
+
+void test_core_oid__is_hexstr(void)
+{
+ cl_assert(git_oid__is_hexstr("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"));
+ cl_assert(!git_oid__is_hexstr("deadbeefdeadbeef"));
+ cl_assert(!git_oid__is_hexstr("zeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"));
+ cl_assert(!git_oid__is_hexstr("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef1"));
+}