| 1 | #include "git-compat-util.h" |
| 2 | #include "hash.h" |
| 3 | #include "oidmap.h" |
| 4 | |
| 5 | static int oidmap_neq(const void *hashmap_cmp_fn_data UNUSED, |
| 6 | const struct hashmap_entry *e1, |
| 7 | const struct hashmap_entry *e2, |
| 8 | const void *keydata) |
| 9 | { |
| 10 | const struct oidmap_entry *a, *b; |
| 11 | |
| 12 | a = container_of(e1, const struct oidmap_entry, internal_entry); |
| 13 | b = container_of(e2, const struct oidmap_entry, internal_entry); |
| 14 | |
| 15 | if (keydata) |
| 16 | return !oideq(&a->oid, (const struct object_id *) keydata); |
| 17 | return !oideq(&a->oid, &b->oid); |
| 18 | } |
| 19 | |
| 20 | void oidmap_init(struct oidmap *map, size_t initial_size) |
| 21 | { |
| 22 | hashmap_init(&map->map, oidmap_neq, NULL, initial_size); |
| 23 | } |
| 24 | |
| 25 | void oidmap_clear(struct oidmap *map, int free_entries) |
| 26 | { |
| 27 | oidmap_clear_with_free(map, |
| 28 | free_entries ? free : NULL); |
| 29 | } |
| 30 | |
| 31 | void oidmap_clear_with_free(struct oidmap *map, |
| 32 | oidmap_free_fn free_fn) |
| 33 | { |
| 34 | struct hashmap_iter iter; |
| 35 | struct hashmap_entry *e; |
| 36 | |
| 37 | if (!map || !map->map.cmpfn) |
| 38 | return; |
| 39 | |
| 40 | hashmap_iter_init(&map->map, &iter); |
| 41 | while ((e = hashmap_iter_next(&iter))) { |
| 42 | struct oidmap_entry *entry = |
| 43 | container_of(e, struct oidmap_entry, internal_entry); |
| 44 | if (free_fn) |
| 45 | free_fn(entry); |
| 46 | } |
| 47 | |
| 48 | hashmap_clear(&map->map); |
| 49 | } |
| 50 | |
| 51 | void *oidmap_get(const struct oidmap *map, const struct object_id *key) |
| 52 | { |
| 53 | if (!map->map.cmpfn) |
| 54 | return NULL; |
| 55 | |
| 56 | return hashmap_get_from_hash(&map->map, oidhash(key), key); |
| 57 | } |
| 58 | |
| 59 | void *oidmap_remove(struct oidmap *map, const struct object_id *key) |
| 60 | { |
| 61 | struct hashmap_entry entry; |
| 62 | |
| 63 | if (!map->map.cmpfn) |
| 64 | oidmap_init(map, 0); |
| 65 | |
| 66 | hashmap_entry_init(&entry, oidhash(key)); |
| 67 | return hashmap_remove(&map->map, &entry, key); |
| 68 | } |
| 69 | |
| 70 | void *oidmap_put(struct oidmap *map, void *entry) |
| 71 | { |
| 72 | struct oidmap_entry *to_put = entry; |
| 73 | |
| 74 | if (!map->map.cmpfn) |
| 75 | oidmap_init(map, 0); |
| 76 | |
| 77 | hashmap_entry_init(&to_put->internal_entry, oidhash(&to_put->oid)); |
| 78 | return hashmap_put(&map->map, &to_put->internal_entry); |
| 79 | } |