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