* bugfix in the hash implementation; expanding the hash wasn't done properly
[citadel.git] / libcitadel / lib / hash.c
1 #include <stdint.h>
2 #include <stdlib.h>
3 #include <string.h>
4 //dbg
5 #include <stdio.h>
6 #include "libcitadel.h"
7 #include "lookup3.h"
8
9 typedef struct Payload Payload;
10
11 struct Payload {
12         /**
13          * \brief Hash Payload storage Structure; filled in linear.
14          */
15         void *Data; /**< the Data belonging to this storage */
16         DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
17 };
18
19 struct HashKey {
20         /**
21          * \brief Hash key element; sorted by key
22          */
23         long Key;         /**< Numeric Hashkey comperator for hash sorting */
24         long Position;    /**< Pointer to a Payload struct in the Payload Aray */
25         char *HashKey;    /**< the Plaintext Hashkey */
26         long HKLen;       /**< length of the Plaintext Hashkey */
27         Payload *PL;      /**< pointer to our payload for sorting */
28 };
29
30 struct HashList {
31         /**
32          * \brief Hash structure; holds arrays of Hashkey and Payload. 
33          */
34         Payload **Members;     /**< Our Payload members. This fills up linear */
35         HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
36         char **MyKeys;         /**< this keeps the members for a call of GetHashKeys */
37         HashFunc Algorithm;    /**< should we use an alternating algorithm to calc the hash values? */
38         long nMembersUsed;     /**< how many pointers inside of the array are used? */
39         long MemberSize;       /**< how big is Members and LookupTable? */
40         long tainted;          /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
41         long uniq;             /**< are the keys going to be uniq? */
42 };
43
44 struct HashPos {
45         /**
46          * \brief Anonymous Hash Iterator Object. used for traversing the whole array from outside 
47          */
48         long Position;
49 };
50
51 /**
52  * \brief verify the contents of a hash list; here for debugging purposes.
53  * \param Hash your Hashlist structure
54  * \param First Functionpointer to allow you to print your payload
55  * \param Second Functionpointer to allow you to print your payload
56  * \returns 0
57  */
58 int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
59 {
60         const char *foo;
61         const char *bar;
62         const char *bla = "";
63         long key;
64         long i;
65         if (Hash->MyKeys != NULL)
66                 free (Hash->MyKeys);
67
68         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
69 #ifdef DEBUG
70         printf("----------------------------------\n");
71 #endif
72         for (i=0; i < Hash->nMembersUsed; i++) {
73                 
74                 if (Hash->LookupTable[i] == NULL)
75                 {
76                         foo = "";
77                         bar = "";
78                         key = 0;
79                 }
80                 else 
81                 {
82                         key = Hash->LookupTable[i]->Key;
83                         foo = Hash->LookupTable[i]->HashKey;
84                         if (First != NULL)
85                                 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
86                         if (Second != NULL)
87                                 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
88                 }
89 #ifdef DEBUG
90                 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
91 #endif
92         }
93 #ifdef DEBUG
94         printf("----------------------------------\n");
95 #endif
96         return 0;
97 }
98
99
100 /**
101  * \brief instanciate a new hashlist
102  * \returns the newly allocated list. 
103  */
104 HashList *NewHash(int Uniq, HashFunc F)
105 {
106         HashList *NewList;
107         NewList = malloc (sizeof(HashList));
108         memset(NewList, 0, sizeof(HashList));
109
110         NewList->Members = malloc(sizeof(Payload*) * 100);
111         memset(NewList->Members, 0, sizeof(Payload*) * 100);
112
113         NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
114         memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
115
116         NewList->MemberSize = 100;
117         NewList->tainted = 0;
118         NewList->uniq = Uniq;
119         NewList->Algorithm = F;
120
121         return NewList;
122 }
123
124 /**
125  * \brief private destructor for one hash element.
126  * \param Data an element to free using the user provided destructor, or just plain free
127  */
128 static void DeleteHashPayload (Payload *Data)
129 {
130         /** do we have a destructor for our payload? */
131         if (Data->Destructor)
132                 Data->Destructor(Data->Data);
133         else
134                 free(Data->Data);
135 }
136
137 /**
138  * \brief destroy a hashlist and all of its members
139  * \param Hash Hash to destroy. Is NULL'ed so you are shure its done.
140  */
141 void DeleteHash(HashList **Hash)
142 {
143         int i;
144         HashList *FreeMe;
145
146         FreeMe = *Hash;
147         if (FreeMe == NULL)
148                 return;
149         for (i=0; i < FreeMe->nMembersUsed; i++)
150         {
151                 /** get rid of our payload */
152                 if (FreeMe->Members[i] != NULL)
153                 {
154                         DeleteHashPayload(FreeMe->Members[i]);
155                         free(FreeMe->Members[i]);
156                 }
157                 /** delete our hashing data */
158                 if (FreeMe->LookupTable[i] != NULL)
159                 {
160                         free(FreeMe->LookupTable[i]->HashKey);
161                         free(FreeMe->LookupTable[i]);
162                 }
163         }
164         /** now, free our arrays... */
165         free(FreeMe->LookupTable);
166         free(FreeMe->Members);
167         /** did s.b. want an array of our keys? free them. */
168         if (FreeMe->MyKeys != NULL)
169                 free(FreeMe->MyKeys);
170         /** buye bye cruel world. */    
171         free (FreeMe);
172         *Hash = NULL;
173 }
174
175 /**
176  * \brief Private function to increase the hash size.
177  * \param Hash the Hasharray to increase
178  */
179 static void IncreaseHashSize(HashList *Hash)
180 {
181         /* Ok, Our space is used up. Double the available space. */
182         Payload **NewPayloadArea;
183         HashKey **NewTable;
184         
185         /** double our payload area */
186         NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
187         memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
188         memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
189         free(Hash->Members);
190         Hash->Members = NewPayloadArea;
191         
192         /** double our hashtable area */
193         NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
194         memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
195         memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
196         free(Hash->LookupTable);
197         Hash->LookupTable = NewTable;
198         
199         Hash->MemberSize *= 2;
200 }
201
202
203 /**
204  * \brief private function to add a new item to / replace an existing in -  the hashlist
205  * if the hash list is full, its re-alloced with double size.
206  * \parame Hash our hashlist to manipulate
207  * \param HashPos where should we insert / replace?
208  * \param HashKeyStr the Hash-String
209  * \param HKLen length of HashKeyStr
210  * \param Data your Payload to add
211  * \param Destructor Functionpointer to free Data. if NULL, default free() is used.
212  */
213 static void InsertHashItem(HashList *Hash, 
214                            long HashPos, 
215                            long HashBinKey, 
216                            const char *HashKeyStr, 
217                            long HKLen, 
218                            void *Data,
219                            DeleteHashDataFunc Destructor)
220 {
221         Payload *NewPayloadItem;
222         HashKey *NewHashKey;
223
224         if (Hash->nMembersUsed >= Hash->MemberSize)
225                 IncreaseHashSize (Hash);
226
227         /** Arrange the payload */
228         NewPayloadItem = (Payload*) malloc (sizeof(Payload));
229         NewPayloadItem->Data = Data;
230         NewPayloadItem->Destructor = Destructor;
231         /** Arrange the hashkey */
232         NewHashKey = (HashKey*) malloc (sizeof(HashKey));
233         NewHashKey->HashKey = (char *) malloc (HKLen + 1);
234         NewHashKey->HKLen = HKLen;
235         memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
236         NewHashKey->Key = HashBinKey;
237         NewHashKey->PL = NewPayloadItem;
238         /** our payload is queued at the end... */
239         NewHashKey->Position = Hash->nMembersUsed;
240         /** but if we should be sorted into a specific place... */
241         if ((Hash->nMembersUsed != 0) && 
242             (HashPos != Hash->nMembersUsed) ) {
243                 long InsertAt;
244                 long ItemsAfter;
245
246                 ItemsAfter = Hash->nMembersUsed - HashPos;
247                 InsertAt = HashPos;
248                 /** make space were we can fill us in */
249                 if (ItemsAfter > 0)
250                 {
251                         memmove(&Hash->LookupTable[InsertAt + 1],
252                                 &Hash->LookupTable[InsertAt],
253                                 ItemsAfter * sizeof(HashKey*));
254                 } 
255         }
256         
257         Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
258         Hash->LookupTable[HashPos] = NewHashKey;
259         Hash->nMembersUsed++;
260 }
261
262 /**
263  * \brief if the user has tainted the hash, but wants to insert / search items by their key
264  *  we need to search linear through the array. You have been warned that this will take more time!
265  * \param Hash Our Hash to manipulate
266  * \param HashBinKey the Hash-Number to lookup. 
267  * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
268  */
269 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
270 {
271         long SearchPos;
272
273         for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
274                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
275                         return SearchPos;
276                 }
277         }
278         return SearchPos;
279 }
280
281 /**
282  * \brief Private function to lookup the Item / the closest position to put it in
283  * \param Hash Our Hash to manipulate
284  * \param HashBinKey the Hash-Number to lookup. 
285  * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
286  */
287 static long FindInHash(HashList *Hash, long HashBinKey)
288 {
289         long SearchPos;
290         long StepWidth;
291
292         if (Hash->tainted)
293                 return FindInTaintedHash(Hash, HashBinKey);
294
295         SearchPos = Hash->nMembersUsed / 2;
296         StepWidth = SearchPos / 2;
297         while ((SearchPos > 0) && 
298                (SearchPos < Hash->nMembersUsed)) 
299         {
300                 /** Did we find it? */
301                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
302                         return SearchPos;
303                 }
304                 /** are we Aproximating in big steps? */
305                 if (StepWidth > 1){
306                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
307                                 SearchPos -= StepWidth;
308                         else
309                                 SearchPos += StepWidth;
310                         StepWidth /= 2;                 
311                 }
312                 else { /** We are right next to our target, within 4 positions */
313                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
314                                 if ((SearchPos > 0) && 
315                                     (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
316                                         return SearchPos;
317                                 SearchPos --;
318                         }
319                         else {
320                                 if ((SearchPos + 1 < Hash->nMembersUsed) && 
321                                     (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
322                                         return SearchPos;
323                                 SearchPos ++;
324                         }
325                         StepWidth--;
326                 }
327         }
328         return SearchPos;
329 }
330
331 /**
332  * \brief private abstract wrapper around the hashing algorithm
333  * \param HKey the hash string
334  * \param HKLen length of HKey
335  * \returns the calculated hash value
336  */
337 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
338 {
339         if (Hash->Algorithm == NULL)
340                 return hashlittle(HKey, HKLen, 9283457);
341         else
342                 return Hash->Algorithm(HKey, HKLen);
343 }
344
345
346 /**
347  * \brief Add a new / Replace an existing item in the Hash
348  * \param HashList the list to manipulate
349  * \param HKey the hash-string to store Data under
350  * \param HKeyLen Length of HKey
351  * \param Data the payload you want to associate with HKey
352  * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
353  */
354 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
355 {
356         long HashBinKey;
357         long HashAt;
358
359         /** first, find out were we could fit in... */
360         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
361         HashAt = FindInHash(Hash, HashBinKey);
362
363         if (HashAt >= Hash->MemberSize)
364                 IncreaseHashSize (Hash);
365
366         /** oh, we're brand new... */
367         if (Hash->LookupTable[HashAt] == NULL) {
368                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
369         }/** Insert After? */
370         else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
371                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
372         }/** Insert before? */
373         else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
374                 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
375         }
376         else { /** Ok, we have a colision. replace it. */
377                 if (Hash->uniq) {
378                         long PayloadPos;
379                         
380                         PayloadPos = Hash->LookupTable[HashAt]->Position;
381                         DeleteHashPayload(Hash->Members[PayloadPos]);
382                         Hash->Members[PayloadPos]->Data = Data;
383                         Hash->Members[PayloadPos]->Destructor = DeleteIt;
384                 }
385                 else {
386                         InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
387                 }
388         }
389 }
390
391 /**
392  * \brief Lookup the Data associated with HKey
393  * \param Hash the Hashlist to search in
394  * \param HKey the hashkey to look up
395  * \param HKLen length of HKey
396  * \param Data returns the Data associated with HKey
397  * \returns 0 if not found, 1 if.
398  */
399 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
400 {
401         long HashBinKey;
402         long HashAt;
403
404         if (HKLen <= 0) {
405                 *Data = NULL;
406                 return  0;
407         }
408         /** first, find out were we could be... */
409         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
410         HashAt = FindInHash(Hash, HashBinKey);
411         if ((HashAt < 0) || /**< Not found at the lower edge? */
412             (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
413             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
414                 *Data = NULL;
415                 return 0;
416         }
417         else { /** GOTCHA! */
418                 long MemberPosition;
419
420                 MemberPosition = Hash->LookupTable[HashAt]->Position;
421                 *Data = Hash->Members[MemberPosition]->Data;
422                 return 1;
423         }
424 }
425
426 /* TODO? */
427 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
428 {
429         return 0;
430 }
431
432 /**
433  * \brief get the Keys present in this hash, simila to array_keys() in PHP
434  *  Attention: List remains to Hash! don't modify or free it!
435  * \param Hash Your Hashlist to extract the keys from
436  * \param List returns the list of hashkeys stored in Hash
437  */
438 int GetHashKeys(HashList *Hash, char ***List)
439 {
440         long i;
441         if (Hash->MyKeys != NULL)
442                 free (Hash->MyKeys);
443
444         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
445         for (i=0; i < Hash->nMembersUsed; i++) {
446         
447                 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
448         }
449         *List = (char**)Hash->MyKeys;
450         return Hash->nMembersUsed;
451 }
452
453 /**
454  * \brief creates a hash-linear iterator object
455  * \returns the hash iterator
456  */
457 HashPos *GetNewHashPos(void)
458 {
459         HashPos *Ret;
460         
461         Ret = (HashPos*)malloc(sizeof(HashPos));
462         Ret->Position = 0;
463         return Ret;
464 }
465
466 /**
467  * \brief frees a linear hash iterator
468  */
469 void DeleteHashPos(HashPos **DelMe)
470 {
471         free(*DelMe);
472         *DelMe = NULL;
473 }
474
475
476 /**
477  * \brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
478  * \param Hash your Hashlist to follow
479  * \param HKLen returns Length of Hashkey Returned
480  * \param HashKey returns the Hashkey corrosponding to HashPos
481  * \param Data returns the Data found at HashPos
482  * \returns whether the item was found or not.
483  */
484 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, char **HashKey, void **Data)
485 {
486         long PayloadPos;
487
488         if (Hash->nMembersUsed <= At->Position)
489                 return 0;
490         *HKLen = Hash->LookupTable[At->Position]->HKLen;
491         *HashKey = Hash->LookupTable[At->Position]->HashKey;
492         PayloadPos = Hash->LookupTable[At->Position]->Position;
493         *Data = Hash->Members[PayloadPos]->Data;
494         At->Position++;
495         return 1;
496 }
497
498 /**
499  * \brief sorting function for sorting the Hash alphabeticaly by their strings
500  * \param Key1 first item
501  * \param Key2 second item
502  */
503 static int SortByKeys(const void *Key1, const void* Key2)
504 {
505         HashKey *HKey1, *HKey2;
506         HKey1 = *(HashKey**) Key1;
507         HKey2 = *(HashKey**) Key2;
508
509         return strcasecmp(HKey1->HashKey, HKey2->HashKey);
510 }
511
512 /**
513  * \brief sorting function to regain hash-sequence and revert tainted status
514  * \param Key1 first item
515  * \param Key2 second item
516  */
517 static int SortByHashKeys(const void *Key1, const void* Key2)
518 {
519         HashKey *HKey1, *HKey2;
520         HKey1 = *(HashKey**) Key1;
521         HKey2 = *(HashKey**) Key2;
522
523         return HKey1->Key > HKey2->Key;
524 }
525
526
527 /**
528  * \brief sort the hash alphabeticaly by their keys.
529  * Caution: This taints the hashlist, so accessing it later 
530  * will be significantly slower! You can un-taint it by SortByHashKeyStr
531  * \param Hash the list to sort
532  */
533 void SortByHashKey(HashList *Hash)
534 {
535         if (Hash->nMembersUsed < 2)
536                 return;
537         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByKeys);
538         Hash->tainted = 1;
539 }
540
541 /**
542  * \brief sort the hash by their keys (so it regains untainted state).
543  * this will result in the sequence the hashing allgorithm produces it by default.
544  * \param Hash the list to sort
545  */
546 void SortByHashKeyStr(HashList *Hash)
547 {
548         Hash->tainted = 0;
549         if (Hash->nMembersUsed < 2)
550                 return;
551         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
552 }
553
554
555 /**
556  * \brief gives user sort routines access to the hash payload
557  * \param Searchentry to retrieve Data to
558  * \returns Data belonging to HashVoid
559  */
560 const void *GetSearchPayload(const void *HashVoid)
561 {
562         return (*(HashKey**)HashVoid)->PL->Data;
563 }
564
565 /**
566  * \brief sort the hash by your sort function. see the following sample.
567  * this will result in the sequence the hashing allgorithm produces it by default.
568  * \param Hash the list to sort
569  * \param SortBy Sortfunction; see below how to implement this
570  */
571 void SortByPayload(HashList *Hash, CompareFunc SortBy)
572 {
573         if (Hash->nMembersUsed < 2)
574                 return;
575         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
576         Hash->tainted = 1;
577 }
578
579
580
581
582 /**
583  * given you've put char * into your hash as a payload, a sort function might
584  * look like this:
585  * int SortByChar(const void* First, const void* Second)
586  * {
587  *      char *a, *b;
588  *      a = (char*) GetSearchPayload(First);
589  *      b = (char*) GetSearchPayload(Second);
590  *      return strcmp (a, b);
591  * }
592  */