lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * This file was taken from http://ccodearchive.net/info/hash.html |
| 3 | * Changes to the original file include cleanups and removal of unwanted code |
| 4 | * and also code that depended on build_asert |
| 5 | */ |
| 6 | #ifndef CCAN_HASH_H |
| 7 | #define CCAN_HASH_H |
| 8 | #include <stdint.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <endian.h> |
| 11 | |
| 12 | /* Stolen mostly from: lookup3.c, by Bob Jenkins, May 2006, Public Domain. |
| 13 | * |
| 14 | * http://burtleburtle.net/bob/c/lookup3.c |
| 15 | */ |
| 16 | |
| 17 | #ifdef __LITTLE_ENDIAN |
| 18 | # define HAVE_LITTLE_ENDIAN 1 |
| 19 | #elif __BIG_ENDIAN |
| 20 | # define HAVE_BIG_ENDIAN 1 |
| 21 | #else |
| 22 | #error Unknown endianness. Failure in endian.h |
| 23 | #endif |
| 24 | |
| 25 | /** |
| 26 | * hash - fast hash of an array for internal use |
| 27 | * @p: the array or pointer to first element |
| 28 | * @num: the number of elements to hash |
| 29 | * @base: the base number to roll into the hash (usually 0) |
| 30 | * |
| 31 | * The memory region pointed to by p is combined with the base to form |
| 32 | * a 32-bit hash. |
| 33 | * |
| 34 | * This hash will have different results on different machines, so is |
| 35 | * only useful for internal hashes (ie. not hashes sent across the |
| 36 | * network or saved to disk). |
| 37 | * |
| 38 | * It may also change with future versions: it could even detect at runtime |
| 39 | * what the fastest hash to use is. |
| 40 | * |
| 41 | * See also: hash64, hash_stable. |
| 42 | * |
| 43 | * Example: |
| 44 | * #include <ccan/hash/hash.h> |
| 45 | * #include <err.h> |
| 46 | * #include <stdio.h> |
| 47 | * #include <string.h> |
| 48 | * |
| 49 | * // Simple demonstration: idential strings will have the same hash, but |
| 50 | * // two different strings will probably not. |
| 51 | * int main(int argc, char *argv[]) |
| 52 | * { |
| 53 | * uint32_t hash1, hash2; |
| 54 | * |
| 55 | * if (argc != 3) |
| 56 | * err(1, "Usage: %s <string1> <string2>", argv[0]); |
| 57 | * |
| 58 | * hash1 = __nl_hash(argv[1], strlen(argv[1]), 0); |
| 59 | * hash2 = __nl_hash(argv[2], strlen(argv[2]), 0); |
| 60 | * printf("Hash is %s\n", hash1 == hash2 ? "same" : "different"); |
| 61 | * return 0; |
| 62 | * } |
| 63 | */ |
| 64 | #define __nl_hash(p, num, base) nl_hash_any((p), (num)*sizeof(*(p)), (base)) |
| 65 | |
| 66 | /* Our underlying operations. */ |
| 67 | uint32_t nl_hash_any(const void *key, size_t length, uint32_t base); |
| 68 | |
| 69 | #endif /* HASH_H */ |