Skip to content

Commit aa24562

Browse files
committed
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.
1 parent 2e0a304 commit aa24562

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

src/offmap.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ size_t git_offmap_size(git_offmap *map)
4242
return kh_size(map);
4343
}
4444

45+
void *git_offmap_get(git_offmap *map, const git_off_t key)
46+
{
47+
size_t idx = git_offmap_lookup_index(map, key);
48+
if (!git_offmap_valid_index(map, idx) ||
49+
!git_offmap_has_data(map, idx))
50+
return NULL;
51+
return kh_val(map, idx);
52+
}
53+
4554
size_t git_offmap_lookup_index(git_offmap *map, const git_off_t key)
4655
{
4756
return kh_get(off, map, key);

src/offmap.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ void git_offmap_clear(git_offmap *map);
5252
*/
5353
size_t git_offmap_size(git_offmap *map);
5454

55+
/**
56+
* Return value associated with the given key.
57+
*
58+
* @param map map to search key in
59+
* @param key key to search for
60+
* @return value associated with the given key or NULL if the key was not found
61+
*/
62+
void *git_offmap_get(git_offmap *map, const git_off_t key);
63+
5564
size_t git_offmap_lookup_index(git_offmap *map, const git_off_t key);
5665
int git_offmap_valid_index(git_offmap *map, size_t idx);
5766

src/pack.c

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,12 @@ static int cache_init(git_pack_cache *cache)
111111

112112
static git_pack_cache_entry *cache_get(git_pack_cache *cache, git_off_t offset)
113113
{
114-
git_pack_cache_entry *entry = NULL;
115-
size_t k;
114+
git_pack_cache_entry *entry;
116115

117116
if (git_mutex_lock(&cache->lock) < 0)
118117
return NULL;
119118

120-
k = git_offmap_lookup_index(cache->entries, offset);
121-
if (git_offmap_valid_index(cache->entries, k)) { /* found it */
122-
entry = git_offmap_value_at(cache->entries, k);
119+
if ((entry = git_offmap_get(cache->entries, offset)) != NULL) {
123120
git_atomic_inc(&entry->refcount);
124121
entry->last_usage = cache->use_ctr++;
125122
}

0 commit comments

Comments
 (0)