Commit aa2456239b4644c43d3cc9e002ed718e5078e7cc

Patrick Steinhardt 2018-11-30T18:28:05

offmap: introduce high-level getter for values The current way of looking up an entry from a map is tightly coupled with the map implementation, as one first has to look up the index of the key and then retrieve the associated value by using the index. As a caller, you usually do not care about any indices at all, though, so this is more complicated than really necessary. Furthermore, it invites for errors to happen if the correct error checking sequence is not being followed. Introduce a new high-level function `git_offmap_get` that takes a map and a key and returns a pointer to the associated value if such a key exists. Otherwise, a `NULL` pointer is returned. Adjust all callers that can trivially be converted.

diff --git a/src/offmap.c b/src/offmap.c
index 2b447b3..561b63c 100644
--- a/src/offmap.c
+++ b/src/offmap.c
@@ -42,6 +42,15 @@ size_t git_offmap_size(git_offmap *map)
 	return kh_size(map);
 }
 
+void *git_offmap_get(git_offmap *map, const git_off_t key)
+{
+	size_t idx = git_offmap_lookup_index(map, key);
+	if (!git_offmap_valid_index(map, idx) ||
+	    !git_offmap_has_data(map, idx))
+		return NULL;
+	return kh_val(map, idx);
+}
+
 size_t git_offmap_lookup_index(git_offmap *map, const git_off_t key)
 {
 	return kh_get(off, map, key);
diff --git a/src/offmap.h b/src/offmap.h
index cde6c31..5491ba7 100644
--- a/src/offmap.h
+++ b/src/offmap.h
@@ -52,6 +52,15 @@ void git_offmap_clear(git_offmap *map);
  */
 size_t git_offmap_size(git_offmap *map);
 
+/**
+ * Return value associated with the given key.
+ *
+ * @param map map to search key in
+ * @param key key to search for
+ * @return value associated with the given key or NULL if the key was not found
+ */
+void *git_offmap_get(git_offmap *map, const git_off_t key);
+
 size_t git_offmap_lookup_index(git_offmap *map, const git_off_t key);
 int git_offmap_valid_index(git_offmap *map, size_t idx);
 
diff --git a/src/pack.c b/src/pack.c
index 650d203..ab78d3f 100644
--- a/src/pack.c
+++ b/src/pack.c
@@ -111,15 +111,12 @@ static int cache_init(git_pack_cache *cache)
 
 static git_pack_cache_entry *cache_get(git_pack_cache *cache, git_off_t offset)
 {
-	git_pack_cache_entry *entry = NULL;
-	size_t k;
+	git_pack_cache_entry *entry;
 
 	if (git_mutex_lock(&cache->lock) < 0)
 		return NULL;
 
-	k = git_offmap_lookup_index(cache->entries, offset);
-	if (git_offmap_valid_index(cache->entries, k)) { /* found it */
-		entry = git_offmap_value_at(cache->entries, k);
+	if ((entry = git_offmap_get(cache->entries, offset)) != NULL) {
 		git_atomic_inc(&entry->refcount);
 		entry->last_usage = cache->use_ctr++;
 	}