hash.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (C) 2008 Red Hat, Inc., Jason Baron <jbaron@redhat.com>
  3. *
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #define DYNAMIC_DEBUG_HASH_BITS 6
  9. static const char *program;
  10. static void usage(void)
  11. {
  12. printf("Usage: %s <djb2|r5> <modname>\n", program);
  13. exit(1);
  14. }
  15. /* djb2 hashing algorithm by Dan Bernstein. From:
  16. * http://www.cse.yorku.ca/~oz/hash.html
  17. */
  18. static unsigned int djb2_hash(char *str)
  19. {
  20. unsigned long hash = 5381;
  21. int c;
  22. c = *str;
  23. while (c) {
  24. hash = ((hash << 5) + hash) + c;
  25. c = *++str;
  26. }
  27. return (unsigned int)(hash & ((1 << DYNAMIC_DEBUG_HASH_BITS) - 1));
  28. }
  29. static unsigned int r5_hash(char *str)
  30. {
  31. unsigned long hash = 0;
  32. int c;
  33. c = *str;
  34. while (c) {
  35. hash = (hash + (c << 4) + (c >> 4)) * 11;
  36. c = *++str;
  37. }
  38. return (unsigned int)(hash & ((1 << DYNAMIC_DEBUG_HASH_BITS) - 1));
  39. }
  40. int main(int argc, char *argv[])
  41. {
  42. program = argv[0];
  43. if (argc != 3)
  44. usage();
  45. if (!strcmp(argv[1], "djb2"))
  46. printf("%d\n", djb2_hash(argv[2]));
  47. else if (!strcmp(argv[1], "r5"))
  48. printf("%d\n", r5_hash(argv[2]));
  49. else
  50. usage();
  51. exit(0);
  52. }