hash.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * category: [algorithm]
  3. * apply status: hashset, shm_table, timerqueue, sp_tbs and mod_sipphone
  4. * edit status: not
  5. * build status:
  6. * description:
  7. */
  8. #ifndef __HASH_H__
  9. #define __HASH_H__
  10. #pragma once
  11. #include "config.h"
  12. #ifdef __cplusplus
  13. extern "C" {
  14. #endif
  15. #define HASH32_BUF_INIT 5381
  16. /*
  17. * uint32_t
  18. * hash32_buf(const void *bf, size_t len, uint32_t hash)
  19. * return a 32 bit hash of the binary buffer buf (size len),
  20. * seeded with an initial hash value of hash (usually HASH32_BUF_INIT).
  21. */
  22. static __inline unsigned int hash32_buf(const void *bf, size_t len, unsigned int hash)
  23. {
  24. const unsigned char *s = (const unsigned char*)bf;
  25. while (len-- != 0) /* "nemesi": k=257, r=r*257 */
  26. hash = hash * 257 + *s++;
  27. return (hash * 257);
  28. }
  29. #define HASH32_STR_INIT 5381
  30. /*
  31. * uint32_t
  32. * hash32_str(const void *bf, uint32_t hash)
  33. * return a 32 bit hash of NUL terminated ASCII string buf,
  34. * seeded with an initial hash value of hash (usually HASH32_STR_INIT).
  35. */
  36. static __inline unsigned int hash32_str(const void *bf, unsigned int hash)
  37. {
  38. const unsigned char *s = (const unsigned char*)bf;
  39. unsigned char c;
  40. while ((c = *s++) != 0)
  41. hash = hash * 33 + c; /* "perl": k=33, r=r+r/32 */
  42. return (hash + (hash >> 5));
  43. }
  44. /*
  45. * unsigned int
  46. * hash32_strn(const void *bf, size_t len, unsigned int hash)
  47. * return a 32 bit hash of NUL terminated ASCII string buf up to
  48. * a maximum of len bytes,
  49. * seeded with an initial hash value of hash (usually HASH32_STR_INIT).
  50. */
  51. static __inline unsigned int hash32_strn(const void *bf, size_t len, unsigned int hash)
  52. {
  53. const unsigned char *s = (const unsigned char *)bf;
  54. unsigned char c;
  55. //while ((c = *s++) != 0 && len-- != 0) // xkm@20160824: sonar fix
  56. while ((c = *s) != 0 && len != 0)
  57. {
  58. s++;
  59. len--;
  60. hash = hash * 33 + c; /* "perl": k=33, r=r+r/32 */
  61. }
  62. return (hash + (hash >> 5));
  63. }
  64. /* used for double hash */
  65. static __inline unsigned int hash_incr(unsigned int h1, unsigned int htable_size)
  66. {
  67. return 1 + ((h1>>5)+1)%(htable_size-1);
  68. }
  69. #ifdef __cplusplus
  70. } // extern "C" {
  71. #endif
  72. #endif //__HASH_H__