Advertisement
Guest User

Untitled

a guest
Jul 4th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #ifndef HTBL_H
  2. #define HTBL_H
  3.  
  4. #ifndef HTBL_HASH
  5. #define HTBL_HASH this->hash
  6. #endif
  7.  
  8. #ifndef HTBL_EQUAL
  9. #define HTBL_EQUAL this->equal
  10. #endif
  11.  
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15.  
  16. typedef struct htbl {
  17.     void **ptr;
  18.     int    sz;
  19.     int  (*hash)(void *, int);
  20.     int  (*equal)(void *, void *);
  21.     int    deleted;
  22. } htbl_t;
  23.  
  24. static inline void htbl_init(htbl_t *this, int sz,
  25.                              int (*hash)(void *, int),
  26.                              int (*equal)(void *, void *))
  27. {
  28.     this->ptr = calloc(sz, sizeof(void *));
  29.     this->sz = sz;
  30.     this->hash = hash;
  31.     this->equal = equal;
  32. }
  33.  
  34. static inline void htbl_free(htbl_t *this, void (*item_free)(void *))
  35. {
  36.     if (item_free) {
  37.         for (int i = 0; i < this->sz; ++i) {
  38.             if (this->ptr[i] == NULL || this->ptr[i] == &this->deleted)
  39.                 continue;
  40.             item_free(this->ptr[i]);
  41.         }
  42.     }
  43.     free(this->ptr);
  44. }
  45.  
  46. static inline void **htbl_find_(htbl_t *this, void *item)
  47. {
  48.     void **pdel = NULL;
  49.     int i, j;
  50.  
  51.     for (i = HTBL_HASH(item, this->sz), j = 1;
  52.          j < this->sz && this->ptr[i];
  53.          i = (i+j)%this->sz, j += 2)
  54.     {
  55.         if (this->ptr[i] == &this->deleted)
  56.             if (!pdel) pdel = &this->ptr[i]; else;
  57.         else
  58.             if (HTBL_EQUAL(this->ptr[i], item)) break;
  59.     }
  60.  
  61.     return j >= this->sz ? pdel
  62.                          : this->ptr[i] || !pdel ? &this->ptr[i]
  63.                                                  : pdel;
  64. }
  65.  
  66. static inline void *htbl_find(htbl_t *this, void *item)
  67. {
  68.     void **pptr = htbl_find_(this, item);
  69.     return pptr && *pptr != &this->deleted ? *pptr
  70.                                            : NULL;
  71. }
  72.  
  73. static inline int htbl_add(htbl_t *this, void *item)
  74. {
  75.     void **pptr = htbl_find_(this, item);
  76.     if (!pptr)
  77.         return -1;
  78.     if (*pptr == NULL || *pptr == &this->deleted)
  79.         *pptr = item;
  80.     return 0;
  81. }
  82.  
  83. static inline void htbl_del(htbl_t *this, void *item)
  84. {
  85.     void **pptr = htbl_find_(this, item);
  86.     if (pptr && *pptr) *pptr = &this->deleted;
  87. }
  88.  
  89. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement