Commit b82d566464baf6616ad26c7a3fdbbb2c68f8f971

Edward Thomson 2022-02-05T09:03:37

oid: introduce git_oid__is_hexstr Introduce a function that determines whether a given string is a valid object id (40 chars of hexadigits).

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"));
+}