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