blob: 8b1bc4dec9496e3b49ba064cc0936925625e5c79 [file] [log] [blame]
Elijah Newren15db4e72023-02-24 00:09:23 +00001#include "git-compat-util.h"
Elijah Newrend1cbe1e2023-04-22 20:17:20 +00002#include "hash.h"
Jonathan Tan9e6fabde2017-09-29 15:54:22 -07003#include "oidmap.h"
4
Ævar Arnfjörð Bjarmason5cf88fd2022-08-25 19:09:48 +02005static int oidmap_neq(const void *hashmap_cmp_fn_data UNUSED,
Eric Wong939af162019-10-06 23:30:37 +00006 const struct hashmap_entry *e1,
7 const struct hashmap_entry *e2,
Jeff Kingcc00e5c2018-08-28 17:22:55 -04008 const void *keydata)
Jonathan Tan9e6fabde2017-09-29 15:54:22 -07009{
Eric Wong939af162019-10-06 23:30:37 +000010 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
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070015 if (keydata)
Eric Wong939af162019-10-06 23:30:37 +000016 return !oideq(&a->oid, (const struct object_id *) keydata);
17 return !oideq(&a->oid, &b->oid);
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070018}
19
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070020void oidmap_init(struct oidmap *map, size_t initial_size)
21{
Jeff Kingcc00e5c2018-08-28 17:22:55 -040022 hashmap_init(&map->map, oidmap_neq, NULL, initial_size);
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070023}
24
25void oidmap_free(struct oidmap *map, int free_entries)
26{
27 if (!map)
28 return;
Eric Wongc8e424c2019-10-06 23:30:40 +000029
30 /* TODO: make oidmap itself not depend on struct layouts */
Elijah Newren6da1a252020-11-02 18:55:05 +000031 hashmap_clear_(&map->map, free_entries ? 0 : -1);
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070032}
33
34void *oidmap_get(const struct oidmap *map, const struct object_id *key)
35{
Brandon Williamse2a5a022017-12-22 15:27:29 -080036 if (!map->map.cmpfn)
37 return NULL;
38
Junio C Hamanoc62bff22019-07-19 11:30:19 -070039 return hashmap_get_from_hash(&map->map, oidhash(key), key);
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070040}
41
42void *oidmap_remove(struct oidmap *map, const struct object_id *key)
43{
44 struct hashmap_entry entry;
Brandon Williamse2a5a022017-12-22 15:27:29 -080045
46 if (!map->map.cmpfn)
47 oidmap_init(map, 0);
48
Junio C Hamanoc62bff22019-07-19 11:30:19 -070049 hashmap_entry_init(&entry, oidhash(key));
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070050 return hashmap_remove(&map->map, &entry, key);
51}
52
53void *oidmap_put(struct oidmap *map, void *entry)
54{
55 struct oidmap_entry *to_put = entry;
Brandon Williamse2a5a022017-12-22 15:27:29 -080056
57 if (!map->map.cmpfn)
58 oidmap_init(map, 0);
59
Junio C Hamanoc62bff22019-07-19 11:30:19 -070060 hashmap_entry_init(&to_put->internal_entry, oidhash(&to_put->oid));
Eric Wong26b455f2019-10-06 23:30:32 +000061 return hashmap_put(&map->map, &to_put->internal_entry);
Jonathan Tan9e6fabde2017-09-29 15:54:22 -070062}