hash.h 1.9 KB

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