hashtable_example.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @file hashtable_example.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #include <stddef.h>
  23. #include <misc/debug.h>
  24. #include <misc/jenkins_hash.h>
  25. #include <structure/HashTable.h>
  26. int key_comparator (int *key1, int *key2)
  27. {
  28. return (*key1 == *key2);
  29. }
  30. int hash_function (int *key, int modulo)
  31. {
  32. return (jenkins_one_at_a_time_hash((uint8_t *)key, sizeof(int)) % modulo);
  33. }
  34. struct entry {
  35. HashTableNode node;
  36. int value;
  37. };
  38. int main ()
  39. {
  40. HashTable table;
  41. if (HashTable_Init(
  42. &table,
  43. (offsetof(struct entry, value) - offsetof(struct entry, node)),
  44. (HashTable_comparator)key_comparator,
  45. (HashTable_hash_function)hash_function,
  46. 20
  47. ) != 1) {
  48. return 1;
  49. }
  50. struct entry entries[10];
  51. // insert entries
  52. int i;
  53. for (i=0; i<10; i++) {
  54. struct entry *entry = &entries[i];
  55. // must initialize value before inserting
  56. entry->value = i;
  57. // insert
  58. int res = HashTable_Insert(&table, &entry->node);
  59. ASSERT(res == 1)
  60. }
  61. // lookup entries
  62. for (i=0; i<10; i++) {
  63. HashTableNode *node;
  64. int res = HashTable_Lookup(&table, &i, &node);
  65. ASSERT(res == 1)
  66. struct entry *entry = (struct entry *)((uint8_t *)node - offsetof(struct entry, node));
  67. ASSERT(entry == &entries[i])
  68. }
  69. // remove entries
  70. for (i=0; i<10; i++) {
  71. int res = HashTable_Remove(&table, &i);
  72. ASSERT(res == 1)
  73. }
  74. // remove entries again
  75. for (i=0; i<10; i++) {
  76. int res = HashTable_Remove(&table, &i);
  77. ASSERT(res == 0)
  78. }
  79. HashTable_Free(&table);
  80. return 0;
  81. }