/src/lib/libc/hash.c

https://github.com/wayling/xboot-clone · C · 74 lines · 24 code · 8 blank · 42 comment · 1 complexity · 4cc4d381ff5dc0871d54515faefb7bda MD5 · raw file

  1. /*
  2. * lib/libc/hash.c
  3. *
  4. * hash function for public.
  5. *
  6. * Copyright (c) 2007-2010 jianjun jiang <jerryjianjun@gmail.com>
  7. * official site: http://xboot.org
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software Foundation,
  21. * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  22. *
  23. */
  24. #include <xboot.h>
  25. #include <string.h>
  26. #include <hash.h>
  27. /*
  28. * calc hash value for a string, copyed from mysql
  29. */
  30. u32_t string_hash(const char * s)
  31. {
  32. u32_t nr=1, nr2=4;
  33. s32_t len = strlen((char*)s);
  34. while(len--)
  35. {
  36. nr ^= ( ( (nr & 63) + nr2 ) * ( (u32_t)(u8_t)*s++) ) + (nr << 8);
  37. nr2 += 3;
  38. }
  39. return( (u32_t)nr);
  40. }
  41. /*
  42. * Fast hashing routine for a long.
  43. *
  44. * Knuth recommends primes in approximately golden ratio to the maximum
  45. * integer representable by a machine word for multiplicative hashing.
  46. * Chuck Lever verified the effectiveness of this technique:
  47. * http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf
  48. *
  49. * These primes are chosen to be bit-sparse, that is operations on
  50. * them can use shifts and additions instead of multiplications for
  51. * machines where multiplications are slow.
  52. *
  53. * 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1
  54. */
  55. inline u32_t long_hash(u32_t val, u32_t bits)
  56. {
  57. u32_t hash = val;
  58. /* On some cpus multiply is faster, on others gcc will do shifts */
  59. hash *= 0x9e370001UL;
  60. /* High bits are more random, so use them. */
  61. return hash >> (32 - bits);
  62. }
  63. inline u32_t ptr_hash(void *ptr, u32_t bits)
  64. {
  65. return long_hash((u32_t)ptr, bits);
  66. }