* more doxygen cleanup
[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 /**
12  * @brief Hash Payload storage Structure; filled in linear.
13  */
14 struct Payload {
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
20 /**
21  * @brief Hash key element; sorted by key
22  */
23 struct HashKey {
24         long Key;         /**< Numeric Hashkey comperator for hash sorting */
25         long Position;    /**< Pointer to a Payload struct in the Payload Aray */
26         char *HashKey;    /**< the Plaintext Hashkey */
27         long HKLen;       /**< length of the Plaintext Hashkey */
28         Payload *PL;      /**< pointer to our payload for sorting */
29 };
30
31 /**
32  * @brief Hash structure; holds arrays of Hashkey and Payload. 
33  */
34 struct HashList {
35         Payload **Members;     /**< Our Payload members. This fills up linear */
36         HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
37         char **MyKeys;         /**< this keeps the members for a call of GetHashKeys */
38         HashFunc Algorithm;    /**< should we use an alternating algorithm to calc the hash values? */
39         long nMembersUsed;     /**< how many pointers inside of the array are used? */
40         long MemberSize;       /**< how big is Members and LookupTable? */
41         long tainted;          /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
42         long uniq;             /**< are the keys going to be uniq? */
43 };
44
45 /**
46  * @brief Anonymous Hash Iterator Object. used for traversing the whole array from outside 
47  */
48 struct HashPos {
49         long Position;        /**< Position inside of the hash */
50         int StepWidth;        /**< small? big? forward? backward? */
51 };
52
53
54 /**
55  * @brief Iterate over the hash and call PrintEntry. 
56  * @param Hash your Hashlist structure
57  * @param Trans is called so you could for example print 'A:' if the next entries are like that.
58  *        Must be aware to receive NULL in both pointers.
59  * @param PrintEntry print entry one by one
60  * \returns the number of items printed
61  */
62 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
63 {
64         int i;
65         void *Previous;
66         void *Next;
67         const char* KeyStr;
68
69         if (Hash == NULL)
70                 return 0;
71
72         for (i=0; i < Hash->nMembersUsed; i++) {
73                 if (i==0) {
74                         Previous = NULL;
75                 }
76                 else {
77                         if (Hash->LookupTable[i - 1] == NULL)
78                                 Previous = NULL;
79                         else
80                                 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
81                 }
82                 if (Hash->LookupTable[i] == NULL) {
83                         KeyStr = "";
84                         Next = NULL;
85                 }
86                 else {
87                         Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
88                         KeyStr = Hash->LookupTable[i]->HashKey;
89                 }
90
91                 Trans(Previous, Next, i % 2);
92                 PrintEntry(KeyStr, Next, i % 2);
93         }
94         return i;
95 }
96
97
98 /**
99  * @brief verify the contents of a hash list; here for debugging purposes.
100  * @param Hash your Hashlist structure
101  * @param First Functionpointer to allow you to print your payload
102  * @param Second Functionpointer to allow you to print your payload
103  * \returns 0
104  */
105 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
106 {
107         const char *foo;
108         const char *bar;
109         const char *bla = "";
110         long key;
111         long i;
112
113         if (Hash == NULL)
114                 return 0;
115
116         if (Hash->MyKeys != NULL)
117                 free (Hash->MyKeys);
118
119         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
120 #ifdef DEBUG
121         printf("----------------------------------\n");
122 #endif
123         for (i=0; i < Hash->nMembersUsed; i++) {
124                 
125                 if (Hash->LookupTable[i] == NULL)
126                 {
127                         foo = "";
128                         bar = "";
129                         key = 0;
130                 }
131                 else 
132                 {
133                         key = Hash->LookupTable[i]->Key;
134                         foo = Hash->LookupTable[i]->HashKey;
135                         if (First != NULL)
136                                 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
137                         else 
138                                 bar = "";
139                         if (Second != NULL)
140                                 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
141                         else
142                                 bla = "";
143                 }
144 #ifdef DEBUG
145                 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
146 #endif
147         }
148 #ifdef DEBUG
149         printf("----------------------------------\n");
150 #endif
151         return 0;
152 }
153
154
155 /**
156  * @brief instanciate a new hashlist
157  * \returns the newly allocated list. 
158  */
159 HashList *NewHash(int Uniq, HashFunc F)
160 {
161         HashList *NewList;
162         NewList = malloc (sizeof(HashList));
163         memset(NewList, 0, sizeof(HashList));
164
165         NewList->Members = malloc(sizeof(Payload*) * 100);
166         memset(NewList->Members, 0, sizeof(Payload*) * 100);
167
168         NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
169         memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
170
171         NewList->MemberSize = 100;
172         NewList->tainted = 0;
173         NewList->uniq = Uniq;
174         NewList->Algorithm = F;
175
176         return NewList;
177 }
178
179 int GetCount(HashList *Hash)
180 {
181         if(Hash==NULL) return 0;
182         return Hash->nMembersUsed;
183 }
184
185
186 /**
187  * @brief private destructor for one hash element.
188  * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
189  * @param Data an element to free using the user provided destructor, or just plain free
190  */
191 static void DeleteHashPayload (Payload *Data)
192 {
193         /** do we have a destructor for our payload? */
194         if (Data->Destructor)
195                 Data->Destructor(Data->Data);
196         else
197                 free(Data->Data);
198 }
199
200 /**
201  * @brief Destructor for nested hashes
202  */
203 void HDeleteHash(void *vHash)
204 {
205         HashList *FreeMe = (HashList*)vHash;
206         DeleteHash(&FreeMe);
207 }
208
209 /**
210  * @brief destroy a hashlist and all of its members
211  * Crashing? do 'print *FreeMe->LookupTable[i]'
212  * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
213  */
214 void DeleteHash(HashList **Hash)
215 {
216         int i;
217         HashList *FreeMe;
218
219         FreeMe = *Hash;
220         if (FreeMe == NULL)
221                 return;
222         for (i=0; i < FreeMe->nMembersUsed; i++)
223         {
224                 /** get rid of our payload */
225                 if (FreeMe->Members[i] != NULL)
226                 {
227                         DeleteHashPayload(FreeMe->Members[i]);
228                         free(FreeMe->Members[i]);
229                 }
230                 /** delete our hashing data */
231                 if (FreeMe->LookupTable[i] != NULL)
232                 {
233                         free(FreeMe->LookupTable[i]->HashKey);
234                         free(FreeMe->LookupTable[i]);
235                 }
236         }
237         /** now, free our arrays... */
238         free(FreeMe->LookupTable);
239         free(FreeMe->Members);
240         /** did s.b. want an array of our keys? free them. */
241         if (FreeMe->MyKeys != NULL)
242                 free(FreeMe->MyKeys);
243         /** buye bye cruel world. */    
244         free (FreeMe);
245         *Hash = NULL;
246 }
247
248 /**
249  * @brief Private function to increase the hash size.
250  * @param Hash the Hasharray to increase
251  */
252 static void IncreaseHashSize(HashList *Hash)
253 {
254         /* Ok, Our space is used up. Double the available space. */
255         Payload **NewPayloadArea;
256         HashKey **NewTable;
257         
258         if (Hash == NULL)
259                 return ;
260
261         /** double our payload area */
262         NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
263         memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
264         memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
265         free(Hash->Members);
266         Hash->Members = NewPayloadArea;
267         
268         /** double our hashtable area */
269         NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
270         memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
271         memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
272         free(Hash->LookupTable);
273         Hash->LookupTable = NewTable;
274         
275         Hash->MemberSize *= 2;
276 }
277
278
279 /**
280  * @brief private function to add a new item to / replace an existing in -  the hashlist
281  * if the hash list is full, its re-alloced with double size.
282  * \parame Hash our hashlist to manipulate
283  * @param HashPos where should we insert / replace?
284  * @param HashKeyStr the Hash-String
285  * @param HKLen length of HashKeyStr
286  * @param Data your Payload to add
287  * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
288  */
289 static void InsertHashItem(HashList *Hash, 
290                            long HashPos, 
291                            long HashBinKey, 
292                            const char *HashKeyStr, 
293                            long HKLen, 
294                            void *Data,
295                            DeleteHashDataFunc Destructor)
296 {
297         Payload *NewPayloadItem;
298         HashKey *NewHashKey;
299
300         if (Hash == NULL)
301                 return;
302
303         if (Hash->nMembersUsed >= Hash->MemberSize)
304                 IncreaseHashSize (Hash);
305
306         /** Arrange the payload */
307         NewPayloadItem = (Payload*) malloc (sizeof(Payload));
308         NewPayloadItem->Data = Data;
309         NewPayloadItem->Destructor = Destructor;
310         /** Arrange the hashkey */
311         NewHashKey = (HashKey*) malloc (sizeof(HashKey));
312         NewHashKey->HashKey = (char *) malloc (HKLen + 1);
313         NewHashKey->HKLen = HKLen;
314         memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
315         NewHashKey->Key = HashBinKey;
316         NewHashKey->PL = NewPayloadItem;
317         /** our payload is queued at the end... */
318         NewHashKey->Position = Hash->nMembersUsed;
319         /** but if we should be sorted into a specific place... */
320         if ((Hash->nMembersUsed != 0) && 
321             (HashPos != Hash->nMembersUsed) ) {
322                 long ItemsAfter;
323
324                 ItemsAfter = Hash->nMembersUsed - HashPos;
325                 /** make space were we can fill us in */
326                 if (ItemsAfter > 0)
327                 {
328                         memmove(&Hash->LookupTable[HashPos + 1],
329                                 &Hash->LookupTable[HashPos],
330                                 ItemsAfter * sizeof(HashKey*));
331                 } 
332         }
333         
334         Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
335         Hash->LookupTable[HashPos] = NewHashKey;
336         Hash->nMembersUsed++;
337 }
338
339 /**
340  * @brief if the user has tainted the hash, but wants to insert / search items by their key
341  *  we need to search linear through the array. You have been warned that this will take more time!
342  * @param Hash Our Hash to manipulate
343  * @param HashBinKey the Hash-Number to lookup. 
344  * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
345  */
346 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
347 {
348         long SearchPos;
349
350         if (Hash == NULL)
351                 return 0;
352
353         for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
354                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
355                         return SearchPos;
356                 }
357         }
358         return SearchPos;
359 }
360
361 /**
362  * @brief Private function to lookup the Item / the closest position to put it in
363  * @param Hash Our Hash to manipulate
364  * @param HashBinKey the Hash-Number to lookup. 
365  * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
366  */
367 static long FindInHash(HashList *Hash, long HashBinKey)
368 {
369         long SearchPos;
370         long StepWidth;
371
372         if (Hash == NULL)
373                 return 0;
374
375         if (Hash->tainted)
376                 return FindInTaintedHash(Hash, HashBinKey);
377
378         SearchPos = Hash->nMembersUsed / 2;
379         StepWidth = SearchPos / 2;
380         while ((SearchPos > 0) && 
381                (SearchPos < Hash->nMembersUsed)) 
382         {
383                 /** Did we find it? */
384                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
385                         return SearchPos;
386                 }
387                 /** are we Aproximating in big steps? */
388                 if (StepWidth > 1){
389                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
390                                 SearchPos -= StepWidth;
391                         else
392                                 SearchPos += StepWidth;
393                         StepWidth /= 2;                 
394                 }
395                 else { /** We are right next to our target, within 4 positions */
396                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
397                                 if ((SearchPos > 0) && 
398                                     (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
399                                         return SearchPos;
400                                 SearchPos --;
401                         }
402                         else {
403                                 if ((SearchPos + 1 < Hash->nMembersUsed) && 
404                                     (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
405                                         return SearchPos;
406                                 SearchPos ++;
407                         }
408                         StepWidth--;
409                 }
410         }
411         return SearchPos;
412 }
413
414
415 /**
416  * @brief another hashing algorithm; treat it as just a pointer to long.
417  * @param str Our pointer to the long value
418  * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
419  * \returns the calculated hash value
420  */
421 int Flathash(const char *str, long len)
422 {
423         if (len != sizeof (int))
424                 return 0;
425         else return *(int*)str;
426 }
427
428 /**
429  * @brief private abstract wrapper around the hashing algorithm
430  * @param HKey the hash string
431  * @param HKLen length of HKey
432  * \returns the calculated hash value
433  */
434 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
435 {
436         if (Hash == NULL)
437                 return 0;
438
439         if (Hash->Algorithm == NULL)
440                 return hashlittle(HKey, HKLen, 9283457);
441         else
442                 return Hash->Algorithm(HKey, HKLen);
443 }
444
445
446 /**
447  * @brief Add a new / Replace an existing item in the Hash
448  * @param HashList the list to manipulate
449  * @param HKey the hash-string to store Data under
450  * @param HKeyLen Length of HKey
451  * @param Data the payload you want to associate with HKey
452  * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
453  */
454 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
455 {
456         long HashBinKey;
457         long HashAt;
458
459         if (Hash == NULL)
460                 return;
461
462         /** first, find out were we could fit in... */
463         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
464         HashAt = FindInHash(Hash, HashBinKey);
465
466         if (HashAt >= Hash->MemberSize)
467                 IncreaseHashSize (Hash);
468
469         /** oh, we're brand new... */
470         if (Hash->LookupTable[HashAt] == NULL) {
471                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
472         }/** Insert After? */
473         else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
474                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
475         }/** Insert before? */
476         else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
477                 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
478         }
479         else { /** Ok, we have a colision. replace it. */
480                 if (Hash->uniq) {
481                         long PayloadPos;
482                         
483                         PayloadPos = Hash->LookupTable[HashAt]->Position;
484                         DeleteHashPayload(Hash->Members[PayloadPos]);
485                         Hash->Members[PayloadPos]->Data = Data;
486                         Hash->Members[PayloadPos]->Destructor = DeleteIt;
487                 }
488                 else {
489                         InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
490                 }
491         }
492 }
493
494 /**
495  * @brief Lookup the Data associated with HKey
496  * @param Hash the Hashlist to search in
497  * @param HKey the hashkey to look up
498  * @param HKLen length of HKey
499  * @param Data returns the Data associated with HKey
500  * \returns 0 if not found, 1 if.
501  */
502 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
503 {
504         long HashBinKey;
505         long HashAt;
506
507         if (Hash == NULL)
508                 return 0;
509
510         if (HKLen <= 0) {
511                 *Data = NULL;
512                 return  0;
513         }
514         /** first, find out were we could be... */
515         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
516         HashAt = FindInHash(Hash, HashBinKey);
517         if ((HashAt < 0) || /**< Not found at the lower edge? */
518             (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
519             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
520                 *Data = NULL;
521                 return 0;
522         }
523         else { /** GOTCHA! */
524                 long MemberPosition;
525
526                 MemberPosition = Hash->LookupTable[HashAt]->Position;
527                 *Data = Hash->Members[MemberPosition]->Data;
528                 return 1;
529         }
530 }
531
532 /* TODO? */
533 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
534 {
535         return 0;
536 }
537
538 /**
539  * @brief get the Keys present in this hash, simila to array_keys() in PHP
540  *  Attention: List remains to Hash! don't modify or free it!
541  * @param Hash Your Hashlist to extract the keys from
542  * @param List returns the list of hashkeys stored in Hash
543  */
544 int GetHashKeys(HashList *Hash, char ***List)
545 {
546         long i;
547         if (Hash == NULL)
548                 return 0;
549         if (Hash->MyKeys != NULL)
550                 free (Hash->MyKeys);
551
552         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
553         for (i=0; i < Hash->nMembersUsed; i++) {
554         
555                 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
556         }
557         *List = (char**)Hash->MyKeys;
558         return Hash->nMembersUsed;
559 }
560
561 /**
562  * @brief creates a hash-linear iterator object
563  * @param Hash the list we reference
564  * @param in which step width should we iterate?
565  *  If negative, the last position matching the 
566  *  step-raster is provided.
567  * \returns the hash iterator
568  */
569 HashPos *GetNewHashPos(HashList *Hash, int StepWidth)
570 {
571         HashPos *Ret;
572         
573         Ret = (HashPos*)malloc(sizeof(HashPos));
574         if (StepWidth != 0)
575                 Ret->StepWidth = StepWidth;
576         else
577                 Ret->StepWidth = 1;
578         if (Ret->StepWidth <  0) {
579                 Ret->Position = Hash->nMembersUsed - 1;
580         }
581         else {
582                 Ret->Position = 0;
583         }
584         return Ret;
585 }
586
587 /**
588  * @brief retrieve the counter from the itteratoor
589  * @param the Iterator to analyze
590  * \returns the n'th hashposition we point at
591  */
592 int GetHashPosCounter(HashList *Hash, HashPos *At)
593 {
594         if ((Hash == NULL) || 
595             (At->Position >= Hash->nMembersUsed) || 
596             (At->Position < 0) ||
597             (At->Position > Hash->nMembersUsed))
598                 return 0;
599         return At->Position;
600 }
601
602 /**
603  * @brief frees a linear hash iterator
604  */
605 void DeleteHashPos(HashPos **DelMe)
606 {
607         if (*DelMe != NULL)
608         {
609                 free(*DelMe);
610                 *DelMe = NULL;
611         }
612 }
613
614
615 /**
616  * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
617  * @param Hash your Hashlist to follow
618  * @param HKLen returns Length of Hashkey Returned
619  * @param HashKey returns the Hashkey corrosponding to HashPos
620  * @param Data returns the Data found at HashPos
621  * \returns whether the item was found or not.
622  */
623 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
624 {
625         long PayloadPos;
626
627         if ((Hash == NULL) || 
628             (At->Position >= Hash->nMembersUsed) || 
629             (At->Position < 0) ||
630             (At->Position > Hash->nMembersUsed))
631                 return 0;
632         *HKLen = Hash->LookupTable[At->Position]->HKLen;
633         *HashKey = Hash->LookupTable[At->Position]->HashKey;
634         PayloadPos = Hash->LookupTable[At->Position]->Position;
635         *Data = Hash->Members[PayloadPos]->Data;
636
637         /* Position is NULL-Based, while Stepwidth is not... */
638         if ((At->Position % abs(At->StepWidth)) == 0)
639                 At->Position += At->StepWidth;
640         else 
641                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
642                         (At->StepWidth / abs(At->StepWidth));
643         return 1;
644 }
645
646 /**
647  * @brief Get the data located where At points to
648  * note: you should prefer iterator operations instead of using me.
649  * @param Hash your Hashlist peek from
650  * @param HKLen returns Length of Hashkey Returned
651  * @param HashKey returns the Hashkey corrosponding to HashPos
652  * @param Data returns the Data found at HashPos
653  * \returns whether the item was found or not.
654  */
655 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
656 {
657         long PayloadPos;
658
659         if ((Hash == NULL) || 
660             (At < 0) || 
661             (At > Hash->nMembersUsed))
662                 return 0;
663         *HKLen = Hash->LookupTable[At]->HKLen;
664         *HashKey = Hash->LookupTable[At]->HashKey;
665         PayloadPos = Hash->LookupTable[At]->Position;
666         *Data = Hash->Members[PayloadPos]->Data;
667         return 1;
668 }
669
670 /**
671  * @brief sorting function for sorting the Hash alphabeticaly by their strings
672  * @param Key1 first item
673  * @param Key2 second item
674  */
675 static int SortByKeys(const void *Key1, const void* Key2)
676 {
677         HashKey *HKey1, *HKey2;
678         HKey1 = *(HashKey**) Key1;
679         HKey2 = *(HashKey**) Key2;
680
681         return strcasecmp(HKey1->HashKey, HKey2->HashKey);
682 }
683
684 /**
685  * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
686  * @param Key1 first item
687  * @param Key2 second item
688  */
689 static int SortByKeysRev(const void *Key1, const void* Key2)
690 {
691         HashKey *HKey1, *HKey2;
692         HKey1 = *(HashKey**) Key1;
693         HKey2 = *(HashKey**) Key2;
694
695         return strcasecmp(HKey2->HashKey, HKey1->HashKey);
696 }
697
698 /**
699  * @brief sorting function to regain hash-sequence and revert tainted status
700  * @param Key1 first item
701  * @param Key2 second item
702  */
703 static int SortByHashKeys(const void *Key1, const void* Key2)
704 {
705         HashKey *HKey1, *HKey2;
706         HKey1 = *(HashKey**) Key1;
707         HKey2 = *(HashKey**) Key2;
708
709         return HKey1->Key > HKey2->Key;
710 }
711
712
713 /**
714  * @brief sort the hash alphabeticaly by their keys.
715  * Caution: This taints the hashlist, so accessing it later 
716  * will be significantly slower! You can un-taint it by SortByHashKeyStr
717  * @param Hash the list to sort
718  * @param Order 0/1 Forward/Backward
719  */
720 void SortByHashKey(HashList *Hash, int Order)
721 {
722         if (Hash->nMembersUsed < 2)
723                 return;
724         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), 
725               (Order)?SortByKeys:SortByKeysRev);
726         Hash->tainted = 1;
727 }
728
729 /**
730  * @brief sort the hash by their keys (so it regains untainted state).
731  * this will result in the sequence the hashing allgorithm produces it by default.
732  * @param Hash the list to sort
733  */
734 void SortByHashKeyStr(HashList *Hash)
735 {
736         Hash->tainted = 0;
737         if (Hash->nMembersUsed < 2)
738                 return;
739         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
740 }
741
742
743 /**
744  * @brief gives user sort routines access to the hash payload
745  * @param Searchentry to retrieve Data to
746  * \returns Data belonging to HashVoid
747  */
748 const void *GetSearchPayload(const void *HashVoid)
749 {
750         return (*(HashKey**)HashVoid)->PL->Data;
751 }
752
753 /**
754  * @brief sort the hash by your sort function. see the following sample.
755  * this will result in the sequence the hashing allgorithm produces it by default.
756  * @param Hash the list to sort
757  * @param SortBy Sortfunction; see below how to implement this
758  */
759 void SortByPayload(HashList *Hash, CompareFunc SortBy)
760 {
761         if (Hash->nMembersUsed < 2)
762                 return;
763         qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
764         Hash->tainted = 1;
765 }
766
767
768
769
770 /**
771  * given you've put char * into your hash as a payload, a sort function might
772  * look like this:
773  * int SortByChar(const void* First, const void* Second)
774  * {
775  *      char *a, *b;
776  *      a = (char*) GetSearchPayload(First);
777  *      b = (char*) GetSearchPayload(Second);
778  *      return strcmp (a, b);
779  * }
780  */
781
782
783 /*
784  * Generic function to free a pointer.  This can be used as a callback with the
785  * hash table, even on systems where free() is defined as a macro or has had other
786  * horrible things done to it.
787  */
788 void generic_free_handler(void *ptr) {
789         free(ptr);
790 }
791
792 /*
793  * Generic function to free a reference.  
794  * since a reference actualy isn't needed to be freed, do nothing.
795  */
796 void reference_free_handler(void *ptr) 
797 {
798         return;
799 }
800
801
802 /*
803  * This exposes the hashlittle() function to consumers.
804  */
805 int HashLittle(const void *key, size_t length) {
806         return (int)hashlittle(key, length, 1);
807 }
808