Commit b7187ed745a066806881d71d248cca66d7cd3f0a

Patrick Steinhardt 2019-02-22T14:38:31

hash: add ability to distinguish algorithms Create an enum that allows us to distinguish between different hashing algorithms. This enum is embedded into each `git_hash_ctx` and will instruct the code to which hashing function the particular request shall be dispatched. As we do not yet have multiple hashing algorithms, we simply initialize the hash algorithm to always be SHA1. At a later point, we will have to extend the `git_hash_init_ctx` function to get as parameter which algorithm shall be used.

diff --git a/src/hash.c b/src/hash.c
index 7d9a41a..ccd8a16 100644
--- a/src/hash.c
+++ b/src/hash.c
@@ -14,27 +14,55 @@ int git_hash_global_init(void)
 
 int git_hash_ctx_init(git_hash_ctx *ctx)
 {
-	return git_hash_sha1_ctx_init(&ctx->sha1);
+	int error;
+
+	if ((error = git_hash_sha1_ctx_init(&ctx->sha1)) < 0)
+		return error;
+
+	ctx->algo = GIT_HASH_ALGO_SHA1;
+
+	return 0;
 }
 
 void git_hash_ctx_cleanup(git_hash_ctx *ctx)
 {
-	git_hash_sha1_ctx_cleanup(&ctx->sha1);
+	switch (ctx->algo) {
+		case GIT_HASH_ALGO_SHA1:
+			git_hash_sha1_ctx_cleanup(&ctx->sha1);
+			return;
+		default:
+			assert(0);
+	}
 }
 
 int git_hash_init(git_hash_ctx *ctx)
 {
-	return git_hash_sha1_init(&ctx->sha1);
+	switch (ctx->algo) {
+		case GIT_HASH_ALGO_SHA1:
+			return git_hash_sha1_init(&ctx->sha1);
+		default:
+			assert(0);
+	}
 }
 
 int git_hash_update(git_hash_ctx *ctx, const void *data, size_t len)
 {
-	return git_hash_sha1_update(&ctx->sha1, data, len);
+	switch (ctx->algo) {
+		case GIT_HASH_ALGO_SHA1:
+			return git_hash_sha1_update(&ctx->sha1, data, len);
+		default:
+			assert(0);
+	}
 }
 
 int git_hash_final(git_oid *out, git_hash_ctx *ctx)
 {
-	return git_hash_sha1_final(out, &ctx->sha1);
+	switch (ctx->algo) {
+		case GIT_HASH_ALGO_SHA1:
+			return git_hash_sha1_final(out, &ctx->sha1);
+		default:
+			assert(0);
+	}
 }
 
 int git_hash_buf(git_oid *out, const void *data, size_t len)
diff --git a/src/hash.h b/src/hash.h
index 18fb5d6..017bb28 100644
--- a/src/hash.h
+++ b/src/hash.h
@@ -17,12 +17,18 @@ typedef struct {
 	size_t len;
 } git_buf_vec;
 
+typedef enum {
+	GIT_HASH_ALGO_UNKNOWN = 0,
+	GIT_HASH_ALGO_SHA1,
+} git_hash_algo_t;
+
 #include "hash/sha1.h"
 
 typedef struct git_hash_ctx {
 	union {
 		git_hash_sha1_ctx sha1;
 	};
+	git_hash_algo_t algo;
 } git_hash_ctx;
 
 int git_hash_global_init(void);