THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

547 lines
18KB

  1. #ifndef HASHMAP_H
  2. #define HASHMAP_H
  3. #include "hash.h"
  4. /*
  5. * Generic implementation of hash-based key-value mappings.
  6. *
  7. * An example that maps long to a string:
  8. * For the sake of the example this allows to lookup exact values, too
  9. * (i.e. it is operated as a set, the value is part of the key)
  10. * -------------------------------------
  11. *
  12. * struct hashmap map;
  13. * struct long2string {
  14. * struct hashmap_entry ent;
  15. * long key;
  16. * char value[FLEX_ARRAY]; // be careful with allocating on stack!
  17. * };
  18. *
  19. * #define COMPARE_VALUE 1
  20. *
  21. * static int long2string_cmp(const void *hashmap_cmp_fn_data,
  22. * const struct hashmap_entry *eptr,
  23. * const struct hashmap_entry *entry_or_key,
  24. * const void *keydata)
  25. * {
  26. * const char *string = keydata;
  27. * unsigned flags = *(unsigned *)hashmap_cmp_fn_data;
  28. * const struct long2string *e1, *e2;
  29. *
  30. * e1 = container_of(eptr, const struct long2string, ent);
  31. * e2 = container_of(entry_or_key, const struct long2string, ent);
  32. *
  33. * if (flags & COMPARE_VALUE)
  34. * return e1->key != e2->key ||
  35. * strcmp(e1->value, string ? string : e2->value);
  36. * else
  37. * return e1->key != e2->key;
  38. * }
  39. *
  40. * int main(int argc, char **argv)
  41. * {
  42. * long key;
  43. * char value[255], action[32];
  44. * unsigned flags = 0;
  45. *
  46. * hashmap_init(&map, long2string_cmp, &flags, 0);
  47. *
  48. * while (scanf("%s %ld %s", action, &key, value)) {
  49. *
  50. * if (!strcmp("add", action)) {
  51. * struct long2string *e;
  52. * FLEX_ALLOC_STR(e, value, value);
  53. * hashmap_entry_init(&e->ent, memhash(&key, sizeof(long)));
  54. * e->key = key;
  55. * hashmap_add(&map, &e->ent);
  56. * }
  57. *
  58. * if (!strcmp("print_all_by_key", action)) {
  59. * struct long2string k, *e;
  60. * hashmap_entry_init(&k->ent, memhash(&key, sizeof(long)));
  61. * k.key = key;
  62. *
  63. * flags &= ~COMPARE_VALUE;
  64. * e = hashmap_get_entry(&map, &k, ent, NULL);
  65. * if (e) {
  66. * printf("first: %ld %s\n", e->key, e->value);
  67. * while ((e = hashmap_get_next_entry(&map, e,
  68. * struct long2string, ent))) {
  69. * printf("found more: %ld %s\n", e->key, e->value);
  70. * }
  71. * }
  72. * }
  73. *
  74. * if (!strcmp("has_exact_match", action)) {
  75. * struct long2string *e;
  76. * FLEX_ALLOC_STR(e, value, value);
  77. * hashmap_entry_init(&e->ent, memhash(&key, sizeof(long)));
  78. * e->key = key;
  79. *
  80. * flags |= COMPARE_VALUE;
  81. * printf("%sfound\n",
  82. * hashmap_get(&map, &e->ent, NULL) ? "" : "not ");
  83. * free(e);
  84. * }
  85. *
  86. * if (!strcmp("has_exact_match_no_heap_alloc", action)) {
  87. * struct long2string k;
  88. * hashmap_entry_init(&k->ent, memhash(&key, sizeof(long)));
  89. * k.key = key;
  90. *
  91. * flags |= COMPARE_VALUE;
  92. * printf("%sfound\n",
  93. * hashmap_get(&map, &k->ent, value) ? "" : "not ");
  94. * }
  95. *
  96. * if (!strcmp("end", action)) {
  97. * hashmap_free_entries(&map, struct long2string, ent);
  98. * break;
  99. * }
  100. * }
  101. *
  102. * return 0;
  103. * }
  104. */
  105. /*
  106. * Ready-to-use hash functions for strings, using the FNV-1 algorithm (see
  107. * http://www.isthe.com/chongo/tech/comp/fnv).
  108. * `strhash` and `strihash` take 0-terminated strings, while `memhash` and
  109. * `memihash` operate on arbitrary-length memory.
  110. * `strihash` and `memihash` are case insensitive versions.
  111. * `memihash_cont` is a variant of `memihash` that allows a computation to be
  112. * continued with another chunk of data.
  113. */
  114. unsigned int strhash(const char *buf);
  115. unsigned int strihash(const char *buf);
  116. unsigned int memhash(const void *buf, size_t len);
  117. unsigned int memihash(const void *buf, size_t len);
  118. unsigned int memihash_cont(unsigned int hash_seed, const void *buf, size_t len);
  119. /*
  120. * Converts a cryptographic hash (e.g. SHA-1) into an int-sized hash code
  121. * for use in hash tables. Cryptographic hashes are supposed to have
  122. * uniform distribution, so in contrast to `memhash()`, this just copies
  123. * the first `sizeof(int)` bytes without shuffling any bits. Note that
  124. * the results will be different on big-endian and little-endian
  125. * platforms, so they should not be stored or transferred over the net.
  126. */
  127. static inline unsigned int oidhash(const struct object_id *oid)
  128. {
  129. /*
  130. * Equivalent to 'return *(unsigned int *)oid->hash;', but safe on
  131. * platforms that don't support unaligned reads.
  132. */
  133. unsigned int hash;
  134. memcpy(&hash, oid->hash, sizeof(hash));
  135. return hash;
  136. }
  137. /*
  138. * struct hashmap_entry is an opaque structure representing an entry in the
  139. * hash table.
  140. * Ideally it should be followed by an int-sized member to prevent unused
  141. * memory on 64-bit systems due to alignment.
  142. */
  143. struct hashmap_entry {
  144. /*
  145. * next points to the next entry in case of collisions (i.e. if
  146. * multiple entries map to the same bucket)
  147. */
  148. struct hashmap_entry *next;
  149. /* entry's hash code */
  150. unsigned int hash;
  151. };
  152. /*
  153. * User-supplied function to test two hashmap entries for equality. Shall
  154. * return 0 if the entries are equal.
  155. *
  156. * This function is always called with non-NULL `entry` and `entry_or_key`
  157. * parameters that have the same hash code.
  158. *
  159. * When looking up an entry, the `key` and `keydata` parameters to hashmap_get
  160. * and hashmap_remove are always passed as second `entry_or_key` and third
  161. * argument `keydata`, respectively. Otherwise, `keydata` is NULL.
  162. *
  163. * When it is too expensive to allocate a user entry (either because it is
  164. * large or varialbe sized, such that it is not on the stack), then the
  165. * relevant data to check for equality should be passed via `keydata`.
  166. * In this case `key` can be a stripped down version of the user key data
  167. * or even just a hashmap_entry having the correct hash.
  168. *
  169. * The `hashmap_cmp_fn_data` entry is the pointer given in the init function.
  170. */
  171. typedef int (*hashmap_cmp_fn)(const void *hashmap_cmp_fn_data,
  172. const struct hashmap_entry *entry,
  173. const struct hashmap_entry *entry_or_key,
  174. const void *keydata);
  175. /*
  176. * struct hashmap is the hash table structure. Members can be used as follows,
  177. * but should not be modified directly.
  178. */
  179. struct hashmap {
  180. struct hashmap_entry **table;
  181. /* Stores the comparison function specified in `hashmap_init()`. */
  182. hashmap_cmp_fn cmpfn;
  183. const void *cmpfn_data;
  184. /* total number of entries (0 means the hashmap is empty) */
  185. unsigned int private_size; /* use hashmap_get_size() */
  186. /*
  187. * tablesize is the allocated size of the hash table. A non-0 value
  188. * indicates that the hashmap is initialized. It may also be useful
  189. * for statistical purposes (i.e. `size / tablesize` is the current
  190. * load factor).
  191. */
  192. unsigned int tablesize;
  193. unsigned int grow_at;
  194. unsigned int shrink_at;
  195. unsigned int do_count_items : 1;
  196. };
  197. /* hashmap functions */
  198. /*
  199. * Initializes a hashmap structure.
  200. *
  201. * `map` is the hashmap to initialize.
  202. *
  203. * The `equals_function` can be specified to compare two entries for equality.
  204. * If NULL, entries are considered equal if their hash codes are equal.
  205. *
  206. * The `equals_function_data` parameter can be used to provide additional data
  207. * (a callback cookie) that will be passed to `equals_function` each time it
  208. * is called. This allows a single `equals_function` to implement multiple
  209. * comparison functions.
  210. *
  211. * If the total number of entries is known in advance, the `initial_size`
  212. * parameter may be used to preallocate a sufficiently large table and thus
  213. * prevent expensive resizing. If 0, the table is dynamically resized.
  214. */
  215. void hashmap_init(struct hashmap *map,
  216. hashmap_cmp_fn equals_function,
  217. const void *equals_function_data,
  218. size_t initial_size);
  219. /* internal function for freeing hashmap */
  220. void hashmap_free_(struct hashmap *map, ssize_t offset);
  221. /*
  222. * Frees a hashmap structure and allocated memory, leaves entries undisturbed
  223. */
  224. #define hashmap_free(map) hashmap_free_(map, -1)
  225. /*
  226. * Frees @map and all entries. @type is the struct type of the entry
  227. * where @member is the hashmap_entry struct used to associate with @map
  228. */
  229. #define hashmap_free_entries(map, type, member) \
  230. hashmap_free_(map, offsetof(type, member));
  231. /* hashmap_entry functions */
  232. /*
  233. * Initializes a hashmap_entry structure.
  234. *
  235. * `entry` points to the entry to initialize.
  236. * `hash` is the hash code of the entry.
  237. *
  238. * The hashmap_entry structure does not hold references to external resources,
  239. * and it is safe to just discard it once you are done with it (i.e. if
  240. * your structure was allocated with xmalloc(), you can just free(3) it,
  241. * and if it is on stack, you can just let it go out of scope).
  242. */
  243. static inline void hashmap_entry_init(struct hashmap_entry *e,
  244. unsigned int hash)
  245. {
  246. e->hash = hash;
  247. e->next = NULL;
  248. }
  249. /*
  250. * Return the number of items in the map.
  251. */
  252. static inline unsigned int hashmap_get_size(struct hashmap *map)
  253. {
  254. if (map->do_count_items)
  255. return map->private_size;
  256. BUG("hashmap_get_size: size not set");
  257. return 0;
  258. }
  259. /*
  260. * Returns the hashmap entry for the specified key, or NULL if not found.
  261. *
  262. * `map` is the hashmap structure.
  263. *
  264. * `key` is a user data structure that starts with hashmap_entry that has at
  265. * least been initialized with the proper hash code (via `hashmap_entry_init`).
  266. *
  267. * `keydata` is a data structure that holds just enough information to check
  268. * for equality to a given entry.
  269. *
  270. * If the key data is variable-sized (e.g. a FLEX_ARRAY string) or quite large,
  271. * it is undesirable to create a full-fledged entry structure on the heap and
  272. * copy all the key data into the structure.
  273. *
  274. * In this case, the `keydata` parameter can be used to pass
  275. * variable-sized key data directly to the comparison function, and the `key`
  276. * parameter can be a stripped-down, fixed size entry structure allocated on the
  277. * stack.
  278. *
  279. * If an entry with matching hash code is found, `key` and `keydata` are passed
  280. * to `hashmap_cmp_fn` to decide whether the entry matches the key.
  281. */
  282. struct hashmap_entry *hashmap_get(const struct hashmap *map,
  283. const struct hashmap_entry *key,
  284. const void *keydata);
  285. /*
  286. * Returns the hashmap entry for the specified hash code and key data,
  287. * or NULL if not found.
  288. *
  289. * `map` is the hashmap structure.
  290. * `hash` is the hash code of the entry to look up.
  291. *
  292. * If an entry with matching hash code is found, `keydata` is passed to
  293. * `hashmap_cmp_fn` to decide whether the entry matches the key. The
  294. * `entry_or_key` parameter of `hashmap_cmp_fn` points to a hashmap_entry
  295. * structure that should not be used in the comparison.
  296. */
  297. static inline struct hashmap_entry *hashmap_get_from_hash(
  298. const struct hashmap *map,
  299. unsigned int hash,
  300. const void *keydata)
  301. {
  302. struct hashmap_entry key;
  303. hashmap_entry_init(&key, hash);
  304. return hashmap_get(map, &key, keydata);
  305. }
  306. /*
  307. * Returns the next equal hashmap entry, or NULL if not found. This can be
  308. * used to iterate over duplicate entries (see `hashmap_add`).
  309. *
  310. * `map` is the hashmap structure.
  311. * `entry` is the hashmap_entry to start the search from, obtained via a previous
  312. * call to `hashmap_get` or `hashmap_get_next`.
  313. */
  314. struct hashmap_entry *hashmap_get_next(const struct hashmap *map,
  315. const struct hashmap_entry *entry);
  316. /*
  317. * Adds a hashmap entry. This allows to add duplicate entries (i.e.
  318. * separate values with the same key according to hashmap_cmp_fn).
  319. *
  320. * `map` is the hashmap structure.
  321. * `entry` is the entry to add.
  322. */
  323. void hashmap_add(struct hashmap *map, struct hashmap_entry *entry);
  324. /*
  325. * Adds or replaces a hashmap entry. If the hashmap contains duplicate
  326. * entries equal to the specified entry, only one of them will be replaced.
  327. *
  328. * `map` is the hashmap structure.
  329. * `entry` is the entry to add or replace.
  330. * Returns the replaced entry, or NULL if not found (i.e. the entry was added).
  331. */
  332. struct hashmap_entry *hashmap_put(struct hashmap *map,
  333. struct hashmap_entry *entry);
  334. /*
  335. * Adds or replaces a hashmap entry contained within @keyvar,
  336. * where @keyvar is a pointer to a struct containing a
  337. * "struct hashmap_entry" @member.
  338. *
  339. * Returns the replaced pointer which is of the same type as @keyvar,
  340. * or NULL if not found.
  341. */
  342. #define hashmap_put_entry(map, keyvar, member) \
  343. container_of_or_null_offset(hashmap_put(map, &(keyvar)->member), \
  344. OFFSETOF_VAR(keyvar, member))
  345. /*
  346. * Removes a hashmap entry matching the specified key. If the hashmap contains
  347. * duplicate entries equal to the specified key, only one of them will be
  348. * removed. Returns the removed entry, or NULL if not found.
  349. *
  350. * Argument explanation is the same as in `hashmap_get`.
  351. */
  352. struct hashmap_entry *hashmap_remove(struct hashmap *map,
  353. const struct hashmap_entry *key,
  354. const void *keydata);
  355. /*
  356. * Removes a hashmap entry contained within @keyvar,
  357. * where @keyvar is a pointer to a struct containing a
  358. * "struct hashmap_entry" @member.
  359. *
  360. * See `hashmap_get` for an explanation of @keydata
  361. *
  362. * Returns the replaced pointer which is of the same type as @keyvar,
  363. * or NULL if not found.
  364. */
  365. #define hashmap_remove_entry(map, keyvar, member, keydata) \
  366. container_of_or_null_offset( \
  367. hashmap_remove(map, &(keyvar)->member, keydata), \
  368. OFFSETOF_VAR(keyvar, member))
  369. /*
  370. * Returns the `bucket` an entry is stored in.
  371. * Useful for multithreaded read access.
  372. */
  373. int hashmap_bucket(const struct hashmap *map, unsigned int hash);
  374. /*
  375. * Used to iterate over all entries of a hashmap. Note that it is
  376. * not safe to add or remove entries to the hashmap while
  377. * iterating.
  378. */
  379. struct hashmap_iter {
  380. struct hashmap *map;
  381. struct hashmap_entry *next;
  382. unsigned int tablepos;
  383. };
  384. /* Initializes a `hashmap_iter` structure. */
  385. void hashmap_iter_init(struct hashmap *map, struct hashmap_iter *iter);
  386. /* Returns the next hashmap_entry, or NULL if there are no more entries. */
  387. struct hashmap_entry *hashmap_iter_next(struct hashmap_iter *iter);
  388. /* Initializes the iterator and returns the first entry, if any. */
  389. static inline struct hashmap_entry *hashmap_iter_first(struct hashmap *map,
  390. struct hashmap_iter *iter)
  391. {
  392. hashmap_iter_init(map, iter);
  393. return hashmap_iter_next(iter);
  394. }
  395. /*
  396. * returns the first entry in @map using @iter, where the entry is of
  397. * @type (e.g. "struct foo") and @member is the name of the
  398. * "struct hashmap_entry" in @type
  399. */
  400. #define hashmap_iter_first_entry(map, iter, type, member) \
  401. container_of_or_null(hashmap_iter_first(map, iter), type, member)
  402. /* internal macro for hashmap_for_each_entry */
  403. #define hashmap_iter_next_entry_offset(iter, offset) \
  404. container_of_or_null_offset(hashmap_iter_next(iter), offset)
  405. /* internal macro for hashmap_for_each_entry */
  406. #define hashmap_iter_first_entry_offset(map, iter, offset) \
  407. container_of_or_null_offset(hashmap_iter_first(map, iter), offset)
  408. /*
  409. * iterate through @map using @iter, @var is a pointer to a type
  410. * containing a @member which is a "struct hashmap_entry"
  411. */
  412. #define hashmap_for_each_entry(map, iter, var, member) \
  413. for (var = hashmap_iter_first_entry_offset(map, iter, \
  414. OFFSETOF_VAR(var, member)); \
  415. var; \
  416. var = hashmap_iter_next_entry_offset(iter, \
  417. OFFSETOF_VAR(var, member)))
  418. /*
  419. * returns a pointer of type matching @keyvar, or NULL if nothing found.
  420. * @keyvar is a pointer to a struct containing a
  421. * "struct hashmap_entry" @member.
  422. */
  423. #define hashmap_get_entry(map, keyvar, member, keydata) \
  424. container_of_or_null_offset( \
  425. hashmap_get(map, &(keyvar)->member, keydata), \
  426. OFFSETOF_VAR(keyvar, member))
  427. #define hashmap_get_entry_from_hash(map, hash, keydata, type, member) \
  428. container_of_or_null(hashmap_get_from_hash(map, hash, keydata), \
  429. type, member)
  430. /*
  431. * returns the next equal pointer to @var, or NULL if not found.
  432. * @var is a pointer of any type containing "struct hashmap_entry"
  433. * @member is the name of the "struct hashmap_entry" field
  434. */
  435. #define hashmap_get_next_entry(map, var, member) \
  436. container_of_or_null_offset(hashmap_get_next(map, &(var)->member), \
  437. OFFSETOF_VAR(var, member))
  438. /*
  439. * iterate @map starting from @var, where @var is a pointer of @type
  440. * and @member is the name of the "struct hashmap_entry" field in @type
  441. */
  442. #define hashmap_for_each_entry_from(map, var, member) \
  443. for (; \
  444. var; \
  445. var = hashmap_get_next_entry(map, var, member))
  446. /*
  447. * Disable item counting and automatic rehashing when adding/removing items.
  448. *
  449. * Normally, the hashmap keeps track of the number of items in the map
  450. * and uses it to dynamically resize it. This (both the counting and
  451. * the resizing) can cause problems when the map is being used by
  452. * threaded callers (because the hashmap code does not know about the
  453. * locking strategy used by the threaded callers and therefore, does
  454. * not know how to protect the "private_size" counter).
  455. */
  456. static inline void hashmap_disable_item_counting(struct hashmap *map)
  457. {
  458. map->do_count_items = 0;
  459. }
  460. /*
  461. * Re-enable item couting when adding/removing items.
  462. * If counting is currently disabled, it will force count them.
  463. * It WILL NOT automatically rehash them.
  464. */
  465. static inline void hashmap_enable_item_counting(struct hashmap *map)
  466. {
  467. unsigned int n = 0;
  468. struct hashmap_iter iter;
  469. if (map->do_count_items)
  470. return;
  471. hashmap_iter_init(map, &iter);
  472. while (hashmap_iter_next(&iter))
  473. n++;
  474. map->do_count_items = 1;
  475. map->private_size = n;
  476. }
  477. /* String interning */
  478. /*
  479. * Returns the unique, interned version of the specified string or data,
  480. * similar to the `String.intern` API in Java and .NET, respectively.
  481. * Interned strings remain valid for the entire lifetime of the process.
  482. *
  483. * Can be used as `[x]strdup()` or `xmemdupz` replacement, except that interned
  484. * strings / data must not be modified or freed.
  485. *
  486. * Interned strings are best used for short strings with high probability of
  487. * duplicates.
  488. *
  489. * Uses a hashmap to store the pool of interned strings.
  490. */
  491. const void *memintern(const void *data, size_t len);
  492. static inline const char *strintern(const char *string)
  493. {
  494. return memintern(string, strlen(string));
  495. }
  496. #endif