Add function to do some revalidations on hashlists; Attention; this can be cpu intens...
[citadel.git] / libcitadel / lib / hash.c
1 #include <stdint.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <limits.h>
5 //dbg
6 #include <stdio.h>
7 #include "libcitadel.h"
8 #include "lookup3.h"
9
10 typedef struct Payload Payload;
11
12 /**
13  * @defgroup HashList Hashlist Key Value list implementation; 
14  * Hashlist is a simple implementation of key value pairs. It doesn't implement collision handling.
15  * the Hashingalgorythm is pluggeable on creation. 
16  * items are added with a functionpointer destructs them; that way complex structures can be added.
17  * if no pointer is given, simply free is used. Use @ref reference_free_handler if you don't want us to free you rmemory.
18  */
19
20 /**
21  * @defgroup HashListData Datastructures used for the internals of HashList
22  * @ingroup HashList
23  */
24
25 /**
26  * @defgroup HashListDebug Hashlist debugging functions
27  * @ingroup HashList
28  */
29
30 /**
31  * @defgroup HashListPrivate Hashlist internal functions
32  * @ingroup HashList
33  */
34
35 /**
36  * @defgroup HashListSort Hashlist sorting functions
37  * @ingroup HashList
38  */
39
40 /**
41  * @defgroup HashListAccess Hashlist functions to access / put / delete items in(to) the list
42  * @ingroup HashList
43  */
44
45 /**
46  * @defgroup HashListAlgorithm functions to condense Key to an integer.
47  * @ingroup HashList
48  */
49
50 /**
51  * @defgroup HashListMset MSet is sort of a derived hashlist, its special for treating Messagesets as Citadel uses them to store access rangesx
52  * @ingroup HashList
53  */
54
55 /**
56  * @ingroup HashListData
57  * @brief Hash Payload storage Structure; filled in linear.
58  */
59 struct Payload {
60         void *Data; /**< the Data belonging to this storage */
61         DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
62 };
63
64
65 /**
66  * @ingroup HashListData
67  * @brief Hash key element; sorted by key
68  */
69 struct HashKey {
70         long Key;         /**< Numeric Hashkey comperator for hash sorting */
71         long Position;    /**< Pointer to a Payload struct in the Payload Aray */
72         char *HashKey;    /**< the Plaintext Hashkey */
73         long HKLen;       /**< length of the Plaintext Hashkey */
74         Payload *PL;      /**< pointer to our payload for sorting */
75 };
76
77 /**
78  * @ingroup HashListData
79  * @brief Hash structure; holds arrays of Hashkey and Payload. 
80  */
81 struct HashList {
82         Payload **Members;     /**< Our Payload members. This fills up linear */
83         HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
84         char **MyKeys;         /**< this keeps the members for a call of GetHashKeys */
85         HashFunc Algorithm;    /**< should we use an alternating algorithm to calc the hash values? */
86         long nMembersUsed;     /**< how many pointers inside of the array are used? */
87         long nLookupTableItems; /**< how many items of the lookup table are used? */
88         long MemberSize;       /**< how big is Members and LookupTable? */
89         long tainted;          /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
90         long uniq;             /**< are the keys going to be uniq? */
91 };
92
93 /**
94  * @ingroup HashListData
95  * @brief Anonymous Hash Iterator Object. used for traversing the whole array from outside 
96  */
97 struct HashPos {
98         long Position;        /**< Position inside of the hash */
99         int StepWidth;        /**< small? big? forward? backward? */
100 };
101
102
103 /**
104  * @ingroup HashListDebug
105  * @brief Iterate over the hash and call PrintEntry. 
106  * @param Hash your Hashlist structure
107  * @param Trans is called so you could for example print 'A:' if the next entries are like that.
108  *        Must be aware to receive NULL in both pointers.
109  * @param PrintEntry print entry one by one
110  * @return the number of items printed
111  */
112 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
113 {
114         int i;
115         void *Previous;
116         void *Next;
117         const char* KeyStr;
118
119         if (Hash == NULL)
120                 return 0;
121
122         for (i=0; i < Hash->nLookupTableItems; i++) {
123                 if (i==0) {
124                         Previous = NULL;
125                 }
126                 else {
127                         if (Hash->LookupTable[i - 1] == NULL)
128                                 Previous = NULL;
129                         else
130                                 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
131                 }
132                 if (Hash->LookupTable[i] == NULL) {
133                         KeyStr = "";
134                         Next = NULL;
135                 }
136                 else {
137                         Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
138                         KeyStr = Hash->LookupTable[i]->HashKey;
139                 }
140
141                 Trans(Previous, Next, i % 2);
142                 PrintEntry(KeyStr, Next, i % 2);
143         }
144         return i;
145 }
146
147
148 /**
149  * @ingroup HashListDebug
150  * @brief verify the contents of a hash list; here for debugging purposes.
151  * @param Hash your Hashlist structure
152  * @param First Functionpointer to allow you to print your payload
153  * @param Second Functionpointer to allow you to print your payload
154  * @return 0
155  */
156 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
157 {
158         const char *foo;
159         const char *bar;
160         const char *bla = "";
161         long key;
162         long i;
163
164         if (Hash == NULL)
165                 return 0;
166
167         if (Hash->MyKeys != NULL)
168                 free (Hash->MyKeys);
169
170         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
171 #ifdef DEBUG
172         printf("----------------------------------\n");
173 #endif
174         for (i=0; i < Hash->nLookupTableItems; i++) {
175                 
176                 if (Hash->LookupTable[i] == NULL)
177                 {
178                         foo = "";
179                         bar = "";
180                         key = 0;
181                 }
182                 else 
183                 {
184                         key = Hash->LookupTable[i]->Key;
185                         foo = Hash->LookupTable[i]->HashKey;
186                         if (First != NULL)
187                                 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
188                         else 
189                                 bar = "";
190                         if (Second != NULL)
191                                 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
192                         else
193                                 bla = "";
194                 }
195 #ifdef DEBUG
196                 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
197 #endif
198         }
199 #ifdef DEBUG
200         printf("----------------------------------\n");
201 #endif
202         return 0;
203 }
204
205
206 int TestValidateHash(HashList *TestHash)
207 {
208         long i;
209
210         if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
211                 return 1;
212
213         if (TestHash->nMembersUsed > TestHash->MemberSize)
214                 return 2;
215
216         for (i=0; i < TestHash->nMembersUsed; i++)
217         {
218
219                 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
220                         return 3;
221                 
222                 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
223                         return 4;
224                 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
225                         return 5;
226         }
227         return 0;
228 }
229
230 /**
231  * @ingroup HashListAccess
232  * @brief instanciate a new hashlist
233  * @return the newly allocated list. 
234  */
235 HashList *NewHash(int Uniq, HashFunc F)
236 {
237         HashList *NewList;
238         NewList = malloc (sizeof(HashList));
239         memset(NewList, 0, sizeof(HashList));
240
241         NewList->Members = malloc(sizeof(Payload*) * 100);
242         memset(NewList->Members, 0, sizeof(Payload*) * 100);
243
244         NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
245         memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
246
247         NewList->MemberSize = 100;
248         NewList->tainted = 0;
249         NewList->uniq = Uniq;
250         NewList->Algorithm = F;
251
252         return NewList;
253 }
254
255 int GetCount(HashList *Hash)
256 {
257         if(Hash==NULL) return 0;
258         return Hash->nLookupTableItems;
259 }
260
261
262 /**
263  * @ingroup HashListPrivate
264  * @brief private destructor for one hash element.
265  * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
266  * @param Data an element to free using the user provided destructor, or just plain free
267  */
268 static void DeleteHashPayload (Payload *Data)
269 {
270         /** do we have a destructor for our payload? */
271         if (Data->Destructor)
272                 Data->Destructor(Data->Data);
273         else
274                 free(Data->Data);
275 }
276
277 /**
278  * @ingroup HashListPrivate
279  * @brief Destructor for nested hashes
280  */
281 void HDeleteHash(void *vHash)
282 {
283         HashList *FreeMe = (HashList*)vHash;
284         DeleteHash(&FreeMe);
285 }
286
287 /**
288  * @ingroup HashListAccess
289  * @brief flush the members of a hashlist 
290  * Crashing? do 'print *FreeMe->LookupTable[i]'
291  * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
292  */
293 void DeleteHashContent(HashList **Hash)
294 {
295         int i;
296         HashList *FreeMe;
297
298         FreeMe = *Hash;
299         if (FreeMe == NULL)
300                 return;
301         /* even if there are sparse members already deleted... */
302         for (i=0; i < FreeMe->nMembersUsed; i++)
303         {
304                 /** get rid of our payload */
305                 if (FreeMe->Members[i] != NULL)
306                 {
307                         DeleteHashPayload(FreeMe->Members[i]);
308                         free(FreeMe->Members[i]);
309                 }
310                 /** delete our hashing data */
311                 if (FreeMe->LookupTable[i] != NULL)
312                 {
313                         free(FreeMe->LookupTable[i]->HashKey);
314                         free(FreeMe->LookupTable[i]);
315                 }
316         }
317         FreeMe->nMembersUsed = 0;
318         FreeMe->tainted = 0;
319         FreeMe->nLookupTableItems = 0;
320         memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
321         memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
322
323         /** did s.b. want an array of our keys? free them. */
324         if (FreeMe->MyKeys != NULL)
325                 free(FreeMe->MyKeys);
326 }
327
328 /**
329  * @ingroup HashListAccess
330  * @brief destroy a hashlist and all of its members
331  * Crashing? do 'print *FreeMe->LookupTable[i]'
332  * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
333  */
334 void DeleteHash(HashList **Hash)
335 {
336         HashList *FreeMe;
337
338         FreeMe = *Hash;
339         if (FreeMe == NULL)
340                 return;
341         DeleteHashContent(Hash);
342         /** now, free our arrays... */
343         free(FreeMe->LookupTable);
344         free(FreeMe->Members);
345
346         /** buye bye cruel world. */    
347         free (FreeMe);
348         *Hash = NULL;
349 }
350
351 /**
352  * @ingroup HashListPrivate
353  * @brief Private function to increase the hash size.
354  * @param Hash the Hasharray to increase
355  */
356 static void IncreaseHashSize(HashList *Hash)
357 {
358         /* Ok, Our space is used up. Double the available space. */
359         Payload **NewPayloadArea;
360         HashKey **NewTable;
361         
362         if (Hash == NULL)
363                 return ;
364
365         /** If we grew to much, this might be the place to rehash and shrink again.
366         if ((Hash->NMembersUsed > Hash->nLookupTableItems) && 
367             ((Hash->NMembersUsed - Hash->nLookupTableItems) > 
368              (Hash->nLookupTableItems / 10)))
369         {
370
371
372         }
373         */
374
375         /** double our payload area */
376         NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
377         memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
378         memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
379         free(Hash->Members);
380         Hash->Members = NewPayloadArea;
381         
382         /** double our hashtable area */
383         NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
384         memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
385         memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
386         free(Hash->LookupTable);
387         Hash->LookupTable = NewTable;
388         
389         Hash->MemberSize *= 2;
390 }
391
392
393 /**
394  * @ingroup HashListPrivate
395  * @brief private function to add a new item to / replace an existing in -  the hashlist
396  * if the hash list is full, its re-alloced with double size.
397  * @param Hash our hashlist to manipulate
398  * @param HashPos where should we insert / replace?
399  * @param HashKeyStr the Hash-String
400  * @param HKLen length of HashKeyStr
401  * @param Data your Payload to add
402  * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
403  */
404 static void InsertHashItem(HashList *Hash, 
405                            long HashPos, 
406                            long HashBinKey, 
407                            const char *HashKeyStr, 
408                            long HKLen, 
409                            void *Data,
410                            DeleteHashDataFunc Destructor)
411 {
412         Payload *NewPayloadItem;
413         HashKey *NewHashKey;
414
415         if (Hash == NULL)
416                 return;
417
418         if (Hash->nMembersUsed >= Hash->MemberSize)
419                 IncreaseHashSize (Hash);
420
421         /** Arrange the payload */
422         NewPayloadItem = (Payload*) malloc (sizeof(Payload));
423         NewPayloadItem->Data = Data;
424         NewPayloadItem->Destructor = Destructor;
425         /** Arrange the hashkey */
426         NewHashKey = (HashKey*) malloc (sizeof(HashKey));
427         NewHashKey->HashKey = (char *) malloc (HKLen + 1);
428         NewHashKey->HKLen = HKLen;
429         memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
430         NewHashKey->Key = HashBinKey;
431         NewHashKey->PL = NewPayloadItem;
432         /** our payload is queued at the end... */
433         NewHashKey->Position = Hash->nMembersUsed;
434         /** but if we should be sorted into a specific place... */
435         if ((Hash->nLookupTableItems != 0) && 
436             (HashPos != Hash->nLookupTableItems) ) {
437                 long ItemsAfter;
438
439                 ItemsAfter = Hash->nLookupTableItems - HashPos;
440                 /** make space were we can fill us in */
441                 if (ItemsAfter > 0)
442                 {
443                         memmove(&Hash->LookupTable[HashPos + 1],
444                                 &Hash->LookupTable[HashPos],
445                                 ItemsAfter * sizeof(HashKey*));
446                 } 
447         }
448         
449         Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
450         Hash->LookupTable[HashPos] = NewHashKey;
451         Hash->nMembersUsed++;
452         Hash->nLookupTableItems++;
453 }
454
455 /**
456  * @ingroup HashListSort
457  * @brief if the user has tainted the hash, but wants to insert / search items by their key
458  *  we need to search linear through the array. You have been warned that this will take more time!
459  * @param Hash Our Hash to manipulate
460  * @param HashBinKey the Hash-Number to lookup. 
461  * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
462  */
463 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
464 {
465         long SearchPos;
466
467         if (Hash == NULL)
468                 return 0;
469
470         for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
471                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
472                         return SearchPos;
473                 }
474         }
475         return SearchPos;
476 }
477
478 /**
479  * @ingroup HashListPrivate
480  * @brief Private function to lookup the Item / the closest position to put it in
481  * @param Hash Our Hash to manipulate
482  * @param HashBinKey the Hash-Number to lookup. 
483  * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
484  */
485 static long FindInHash(HashList *Hash, long HashBinKey)
486 {
487         long SearchPos;
488         long StepWidth;
489
490         if (Hash == NULL)
491                 return 0;
492
493         if (Hash->tainted)
494                 return FindInTaintedHash(Hash, HashBinKey);
495
496         SearchPos = Hash->nLookupTableItems / 2;
497         StepWidth = SearchPos / 2;
498         while ((SearchPos > 0) && 
499                (SearchPos < Hash->nLookupTableItems)) 
500         {
501                 /** Did we find it? */
502                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
503                         return SearchPos;
504                 }
505                 /** are we Aproximating in big steps? */
506                 if (StepWidth > 1){
507                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
508                                 SearchPos -= StepWidth;
509                         else
510                                 SearchPos += StepWidth;
511                         StepWidth /= 2;                 
512                 }
513                 else { /** We are right next to our target, within 4 positions */
514                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
515                                 if ((SearchPos > 0) && 
516                                     (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
517                                         return SearchPos;
518                                 SearchPos --;
519                         }
520                         else {
521                                 if ((SearchPos + 1 < Hash->nLookupTableItems) && 
522                                     (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
523                                         return SearchPos;
524                                 SearchPos ++;
525                         }
526                         StepWidth--;
527                 }
528         }
529         return SearchPos;
530 }
531
532
533 /**
534  * @ingroup HashListAlgorithm
535  * @brief another hashing algorithm; treat it as just a pointer to int.
536  * @param str Our pointer to the int value
537  * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
538  * @return the calculated hash value
539  */
540 long Flathash(const char *str, long len)
541 {
542         if (len != sizeof (int))
543                 return 0;
544         else return *(int*)str;
545 }
546
547 /**
548  * @ingroup HashListAlgorithm
549  * @brief another hashing algorithm; treat it as just a pointer to long.
550  * @param str Our pointer to the long value
551  * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
552  * @return the calculated hash value
553  */
554 long lFlathash(const char *str, long len)
555 {
556         if (len != sizeof (long))
557                 return 0;
558         else return *(long*)str;
559 }
560
561 /**
562  * @ingroup HashListPrivate
563  * @brief private abstract wrapper around the hashing algorithm
564  * @param HKey the hash string
565  * @param HKLen length of HKey
566  * @return the calculated hash value
567  */
568 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
569 {
570         if (Hash == NULL)
571                 return 0;
572
573         if (Hash->Algorithm == NULL)
574                 return hashlittle(HKey, HKLen, 9283457);
575         else
576                 return Hash->Algorithm(HKey, HKLen);
577 }
578
579
580 /**
581  * @ingroup HashListAccess
582  * @brief Add a new / Replace an existing item in the Hash
583  * @param Hash the list to manipulate
584  * @param HKey the hash-string to store Data under
585  * @param HKLen Length of HKey
586  * @param Data the payload you want to associate with HKey
587  * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
588  */
589 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
590 {
591         long HashBinKey;
592         long HashAt;
593
594         if (Hash == NULL)
595                 return;
596
597         /** first, find out were we could fit in... */
598         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
599         HashAt = FindInHash(Hash, HashBinKey);
600
601         if (HashAt >= Hash->MemberSize)
602                 IncreaseHashSize (Hash);
603
604         /** oh, we're brand new... */
605         if (Hash->LookupTable[HashAt] == NULL) {
606                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
607         }/** Insert After? */
608         else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
609                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
610         }/** Insert before? */
611         else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
612                 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
613         }
614         else { /** Ok, we have a colision. replace it. */
615                 if (Hash->uniq) {
616                         long PayloadPos;
617                         
618                         PayloadPos = Hash->LookupTable[HashAt]->Position;
619                         DeleteHashPayload(Hash->Members[PayloadPos]);
620                         Hash->Members[PayloadPos]->Data = Data;
621                         Hash->Members[PayloadPos]->Destructor = DeleteIt;
622                 }
623                 else {
624                         InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
625                 }
626         }
627 }
628
629 /**
630  * @ingroup HashListAccess
631  * @brief Lookup the Data associated with HKey
632  * @param Hash the Hashlist to search in
633  * @param HKey the hashkey to look up
634  * @param HKLen length of HKey
635  * @param Data returns the Data associated with HKey
636  * @return 0 if not found, 1 if.
637  */
638 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
639 {
640         long HashBinKey;
641         long HashAt;
642
643         if (Hash == NULL)
644                 return 0;
645
646         if (HKLen <= 0) {
647                 *Data = NULL;
648                 return  0;
649         }
650         /** first, find out were we could be... */
651         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
652         HashAt = FindInHash(Hash, HashBinKey);
653         if ((HashAt < 0) || /**< Not found at the lower edge? */
654             (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
655             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
656                 *Data = NULL;
657                 return 0;
658         }
659         else { /** GOTCHA! */
660                 long MemberPosition;
661
662                 MemberPosition = Hash->LookupTable[HashAt]->Position;
663                 *Data = Hash->Members[MemberPosition]->Data;
664                 return 1;
665         }
666 }
667
668 /* TODO? */
669 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
670 {
671         return 0;
672 }
673
674 /**
675  * @ingroup HashListAccess
676  * @brief get the Keys present in this hash, simila to array_keys() in PHP
677  *  Attention: List remains to Hash! don't modify or free it!
678  * @param Hash Your Hashlist to extract the keys from
679  * @param List returns the list of hashkeys stored in Hash
680  */
681 int GetHashKeys(HashList *Hash, char ***List)
682 {
683         long i;
684         if (Hash == NULL)
685                 return 0;
686         if (Hash->MyKeys != NULL)
687                 free (Hash->MyKeys);
688
689         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
690         for (i=0; i < Hash->nLookupTableItems; i++) {
691         
692                 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
693         }
694         *List = (char**)Hash->MyKeys;
695         return Hash->nLookupTableItems;
696 }
697
698 /**
699  * @ingroup HashListAccess
700  * @brief creates a hash-linear iterator object
701  * @param Hash the list we reference
702  * @param StepWidth in which step width should we iterate?
703  *  If negative, the last position matching the 
704  *  step-raster is provided.
705  * @return the hash iterator
706  */
707 HashPos *GetNewHashPos(HashList *Hash, int StepWidth)
708 {
709         HashPos *Ret;
710         
711         Ret = (HashPos*)malloc(sizeof(HashPos));
712         if (StepWidth != 0)
713                 Ret->StepWidth = StepWidth;
714         else
715                 Ret->StepWidth = 1;
716         if (Ret->StepWidth <  0) {
717                 Ret->Position = Hash->nLookupTableItems - 1;
718         }
719         else {
720                 Ret->Position = 0;
721         }
722         return Ret;
723 }
724
725 /**
726  * @ingroup HashListAccess
727  * @brief Set iterator object to point to key. If not found, don't change iterator
728  * @param Hash the list we reference
729  * @param HKey key to search for
730  * @param HKLen length of key
731  * @param At HashPos to update
732  * @return 0 if not found
733  */
734 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
735 {
736         long HashBinKey;
737         long HashAt;
738
739         if (Hash == NULL)
740                 return 0;
741
742         if (HKLen <= 0) {
743                 return  0;
744         }
745         /** first, find out were we could be... */
746         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
747         HashAt = FindInHash(Hash, HashBinKey);
748         if ((HashAt < 0) || /**< Not found at the lower edge? */
749             (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
750             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
751                 return 0;
752         }
753         /** GOTCHA! */
754         At->Position = Hash->LookupTable[HashAt]->Position;
755         return 1;
756 }
757
758 /**
759  * @ingroup HashListAccess
760  * @brief Delete from the Hash the entry at Position
761  * @param Hash the list we reference
762  * @param At the position within the Hash
763  * @return 0 if not found
764  */
765 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
766 {
767         Payload *FreeMe;
768         if (Hash == NULL)
769                 return 0;
770
771         /* if lockable, lock here */
772         if ((Hash == NULL) || 
773             (At->Position >= Hash->nLookupTableItems) || 
774             (At->Position < 0) ||
775             (At->Position > Hash->nLookupTableItems))
776         {
777                 /* unlock... */
778                 return 0;
779         }
780
781         FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
782         Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
783
784
785         /** delete our hashing data */
786         if (Hash->LookupTable[At->Position] != NULL)
787         {
788                 free(Hash->LookupTable[At->Position]->HashKey);
789                 free(Hash->LookupTable[At->Position]);
790                 if (At->Position < Hash->nLookupTableItems)
791                 {
792                         memmove(&Hash->LookupTable[At->Position],
793                                 &Hash->LookupTable[At->Position + 1],
794                                 (Hash->nLookupTableItems - At->Position - 1) * 
795                                 sizeof(HashKey*));
796
797                         Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
798                 }
799                 else 
800                         Hash->LookupTable[At->Position] = NULL;
801                 Hash->nLookupTableItems--;
802         }
803         /* unlock... */
804
805
806         /** get rid of our payload */
807         if (FreeMe != NULL)
808         {
809                 DeleteHashPayload(FreeMe);
810                 free(FreeMe);
811         }
812         return 1;
813 }
814
815 /**
816  * @ingroup HashListAccess
817  * @brief retrieve the counter from the itteratoor
818  * @param Hash which 
819  * @param At the Iterator to analyze
820  * @return the n'th hashposition we point at
821  */
822 int GetHashPosCounter(HashList *Hash, HashPos *At)
823 {
824         if ((Hash == NULL) || 
825             (At->Position >= Hash->nLookupTableItems) || 
826             (At->Position < 0) ||
827             (At->Position > Hash->nLookupTableItems))
828                 return 0;
829         return At->Position;
830 }
831
832 /**
833  * @ingroup HashListAccess
834  * @brief frees a linear hash iterator
835  */
836 void DeleteHashPos(HashPos **DelMe)
837 {
838         if (*DelMe != NULL)
839         {
840                 free(*DelMe);
841                 *DelMe = NULL;
842         }
843 }
844
845
846 /**
847  * @ingroup HashListAccess
848  * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
849  * @param Hash your Hashlist to follow
850  * @param At the position to retrieve the Item from and move forward afterwards
851  * @param HKLen returns Length of Hashkey Returned
852  * @param HashKey returns the Hashkey corrosponding to HashPos
853  * @param Data returns the Data found at HashPos
854  * @return whether the item was found or not.
855  */
856 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
857 {
858         long PayloadPos;
859
860         if ((Hash == NULL) || 
861             (At->Position >= Hash->nLookupTableItems) || 
862             (At->Position < 0) ||
863             (At->Position > Hash->nLookupTableItems))
864                 return 0;
865         *HKLen = Hash->LookupTable[At->Position]->HKLen;
866         *HashKey = Hash->LookupTable[At->Position]->HashKey;
867         PayloadPos = Hash->LookupTable[At->Position]->Position;
868         *Data = Hash->Members[PayloadPos]->Data;
869
870         /* Position is NULL-Based, while Stepwidth is not... */
871         if ((At->Position % abs(At->StepWidth)) == 0)
872                 At->Position += At->StepWidth;
873         else 
874                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
875                         (At->StepWidth / abs(At->StepWidth));
876         return 1;
877 }
878
879 /**
880  * @ingroup HashListAccess
881  * @brief Get the data located where HashPos Iterator points at
882  * @param Hash your Hashlist to follow
883  * @param At the position retrieve the data from
884  * @param HKLen returns Length of Hashkey Returned
885  * @param HashKey returns the Hashkey corrosponding to HashPos
886  * @param Data returns the Data found at HashPos
887  * @return whether the item was found or not.
888  */
889 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
890 {
891         long PayloadPos;
892
893         if ((Hash == NULL) || 
894             (At->Position >= Hash->nLookupTableItems) || 
895             (At->Position < 0) ||
896             (At->Position > Hash->nLookupTableItems))
897                 return 0;
898         *HKLen = Hash->LookupTable[At->Position]->HKLen;
899         *HashKey = Hash->LookupTable[At->Position]->HashKey;
900         PayloadPos = Hash->LookupTable[At->Position]->Position;
901         *Data = Hash->Members[PayloadPos]->Data;
902
903         return 1;
904 }
905
906 /**
907  * @ingroup HashListAccess
908  * @brief Move HashPos one forward
909  * @param Hash your Hashlist to follow
910  * @param At the position to move forward
911  * @return whether there is a next item or not.
912  */
913 int NextHashPos(HashList *Hash, HashPos *At)
914 {
915         if ((Hash == NULL) || 
916             (At->Position >= Hash->nLookupTableItems) || 
917             (At->Position < 0) ||
918             (At->Position > Hash->nLookupTableItems))
919                 return 0;
920
921         /* Position is NULL-Based, while Stepwidth is not... */
922         if ((At->Position % abs(At->StepWidth)) == 0)
923                 At->Position += At->StepWidth;
924         else 
925                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
926                         (At->StepWidth / abs(At->StepWidth));
927         return !((At->Position >= Hash->nLookupTableItems) || 
928                  (At->Position < 0) ||
929                  (At->Position > Hash->nLookupTableItems));
930 }
931
932 /**
933  * @ingroup HashListAccess
934  * @brief Get the data located where At points to
935  * note: you should prefer iterator operations instead of using me.
936  * @param Hash your Hashlist peek from
937  * @param At get the item in the position At.
938  * @param HKLen returns Length of Hashkey Returned
939  * @param HashKey returns the Hashkey corrosponding to HashPos
940  * @param Data returns the Data found at HashPos
941  * @return whether the item was found or not.
942  */
943 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
944 {
945         long PayloadPos;
946
947         if ((Hash == NULL) || 
948             (At < 0) || 
949             (At >= Hash->nLookupTableItems))
950                 return 0;
951         *HKLen = Hash->LookupTable[At]->HKLen;
952         *HashKey = Hash->LookupTable[At]->HashKey;
953         PayloadPos = Hash->LookupTable[At]->Position;
954         *Data = Hash->Members[PayloadPos]->Data;
955         return 1;
956 }
957
958 /**
959  * @ingroup HashListSort
960  * @brief Get the data located where At points to
961  * note: you should prefer iterator operations instead of using me.
962  * @param Hash your Hashlist peek from
963  * @param HKLen returns Length of Hashkey Returned
964  * @param HashKey returns the Hashkey corrosponding to HashPos
965  * @param Data returns the Data found at HashPos
966  * @return whether the item was found or not.
967  */
968 /*
969 long GetHashIDAt(HashList *Hash,long At)
970 {
971         if ((Hash == NULL) || 
972             (At < 0) || 
973             (At > Hash->nLookupTableItems))
974                 return 0;
975
976         return Hash->LookupTable[At]->Key;
977 }
978 */
979
980
981 /**
982  * @ingroup HashListSort
983  * @brief sorting function for sorting the Hash alphabeticaly by their strings
984  * @param Key1 first item
985  * @param Key2 second item
986  */
987 static int SortByKeys(const void *Key1, const void* Key2)
988 {
989         HashKey *HKey1, *HKey2;
990         HKey1 = *(HashKey**) Key1;
991         HKey2 = *(HashKey**) Key2;
992
993         return strcasecmp(HKey1->HashKey, HKey2->HashKey);
994 }
995
996 /**
997  * @ingroup HashListSort
998  * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
999  * @param Key1 first item
1000  * @param Key2 second item
1001  */
1002 static int SortByKeysRev(const void *Key1, const void* Key2)
1003 {
1004         HashKey *HKey1, *HKey2;
1005         HKey1 = *(HashKey**) Key1;
1006         HKey2 = *(HashKey**) Key2;
1007
1008         return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1009 }
1010
1011 /**
1012  * @ingroup HashListSort
1013  * @brief sorting function to regain hash-sequence and revert tainted status
1014  * @param Key1 first item
1015  * @param Key2 second item
1016  */
1017 static int SortByHashKeys(const void *Key1, const void* Key2)
1018 {
1019         HashKey *HKey1, *HKey2;
1020         HKey1 = *(HashKey**) Key1;
1021         HKey2 = *(HashKey**) Key2;
1022
1023         return HKey1->Key > HKey2->Key;
1024 }
1025
1026
1027 /**
1028  * @ingroup HashListSort
1029  * @brief sort the hash alphabeticaly by their keys.
1030  * Caution: This taints the hashlist, so accessing it later 
1031  * will be significantly slower! You can un-taint it by SortByHashKeyStr
1032  * @param Hash the list to sort
1033  * @param Order 0/1 Forward/Backward
1034  */
1035 void SortByHashKey(HashList *Hash, int Order)
1036 {
1037         if (Hash->nLookupTableItems < 2)
1038                 return;
1039         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), 
1040               (Order)?SortByKeys:SortByKeysRev);
1041         Hash->tainted = 1;
1042 }
1043
1044 /**
1045  * @ingroup HashListSort
1046  * @brief sort the hash by their keys (so it regains untainted state).
1047  * this will result in the sequence the hashing allgorithm produces it by default.
1048  * @param Hash the list to sort
1049  */
1050 void SortByHashKeyStr(HashList *Hash)
1051 {
1052         Hash->tainted = 0;
1053         if (Hash->nLookupTableItems < 2)
1054                 return;
1055         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1056 }
1057
1058
1059 /**
1060  * @ingroup HashListSort
1061  * @brief gives user sort routines access to the hash payload
1062  * @param HashVoid to retrieve Data to
1063  * @return Data belonging to HashVoid
1064  */
1065 const void *GetSearchPayload(const void *HashVoid)
1066 {
1067         return (*(HashKey**)HashVoid)->PL->Data;
1068 }
1069
1070 /**
1071  * @ingroup HashListSort
1072  * @brief sort the hash by your sort function. see the following sample.
1073  * this will result in the sequence the hashing allgorithm produces it by default.
1074  * @param Hash the list to sort
1075  * @param SortBy Sortfunction; see below how to implement this
1076  */
1077 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1078 {
1079         if (Hash->nLookupTableItems < 2)
1080                 return;
1081         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1082         Hash->tainted = 1;
1083 }
1084
1085
1086
1087
1088 /**
1089  * given you've put char * into your hash as a payload, a sort function might
1090  * look like this:
1091  * int SortByChar(const void* First, const void* Second)
1092  * {
1093  *      char *a, *b;
1094  *      a = (char*) GetSearchPayload(First);
1095  *      b = (char*) GetSearchPayload(Second);
1096  *      return strcmp (a, b);
1097  * }
1098  */
1099
1100
1101 /**
1102  * @ingroup HashListAccess
1103  * @brief Generic function to free a reference.  
1104  * since a reference actualy isn't needed to be freed, do nothing.
1105  */
1106 void reference_free_handler(void *ptr) 
1107 {
1108         return;
1109 }
1110
1111
1112 /**
1113  * @ingroup HashListAlgorithm
1114  * This exposes the hashlittle() function to consumers.
1115  */
1116 int HashLittle(const void *key, size_t length) {
1117         return (int)hashlittle(key, length, 1);
1118 }
1119
1120
1121 /**
1122  * @ingroup HashListMset
1123  * @brief parses an MSet string into a list for later use
1124  * @param MSetList List to be read from MSetStr
1125  * @param MSetStr String containing the list
1126  */
1127 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1128 {
1129         const char *POS = NULL, *SetPOS = NULL;
1130         StrBuf *OneSet;
1131         HashList *ThisMSet;
1132         long StartSet, EndSet;
1133         long *pEndSet;
1134         
1135         *MSetList = NULL;
1136         if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1137             return 0;
1138             
1139         OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1140
1141         ThisMSet = NewHash(0, lFlathash);
1142
1143         *MSetList = (MSet*) ThisMSet;
1144
1145         /* an MSet is a coma separated value list. */
1146         StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1147         do {
1148                 SetPOS = NULL;
1149
1150                 /* One set may consist of two Numbers: Start + optional End */
1151                 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1152                 EndSet = 0; /* no range is our default. */
1153                 /* do we have an end (aka range?) */
1154                 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1155                 {
1156                         if (*(SetPOS) == '*')
1157                                 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1158                         else 
1159                                 /* in other cases, get the EndPoint */
1160                                 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1161                 }
1162
1163                 pEndSet = (long*) malloc (sizeof(long));
1164                 *pEndSet = EndSet;
1165
1166                 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1167                 /* if we don't have another, we're done. */
1168                 if (POS == StrBufNOTNULL)
1169                         break;
1170                 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1171         } while (1);
1172         FreeStrBuf(&OneSet);
1173
1174         return 1;
1175 }
1176
1177 /**
1178  * @ingroup HashListMset
1179  * @brief checks whether a message is inside a mset
1180  * @param MSetList List to search for MsgNo
1181  * @param MsgNo number to search in mset
1182  */
1183 int IsInMSetList(MSet *MSetList, long MsgNo)
1184 {
1185         /* basicaly we are a ... */
1186         long MemberPosition;
1187         HashList *Hash = (HashList*) MSetList;
1188         long HashAt;
1189         long EndAt;
1190         long StartAt;
1191
1192         if (Hash == NULL)
1193                 return 0;
1194         if (Hash->MemberSize == 0)
1195                 return 0;
1196         /** first, find out were we could fit in... */
1197         HashAt = FindInHash(Hash, MsgNo);
1198         
1199         /* we're below the first entry, so not found. */
1200         if (HashAt < 0)
1201                 return 0;
1202         /* upper edge? move to last item */
1203         if (HashAt >= Hash->nMembersUsed)
1204                 HashAt = Hash->nMembersUsed - 1;
1205         /* Match? then we got it. */
1206         else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1207                 return 1;
1208         /* One above possible range start? we need to move to the lower one. */ 
1209         else if ((HashAt > 0) && 
1210                  (Hash->LookupTable[HashAt]->Key > MsgNo))
1211                 HashAt -=1;
1212
1213         /* Fetch the actual data */
1214         StartAt = Hash->LookupTable[HashAt]->Key;
1215         MemberPosition = Hash->LookupTable[HashAt]->Position;
1216         EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1217         if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1218                 return 1;
1219         /* no range? */
1220         if (EndAt == 0)
1221                 return 0;
1222         /* inside of range? */
1223         if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1224                 return 1;
1225         return 0;
1226 }
1227
1228
1229 /**
1230  * @ingroup HashListMset
1231  * @brief frees a mset [redirects to @ref DeleteHash
1232  * @param FreeMe to be free'd
1233  */
1234 void DeleteMSet(MSet **FreeMe)
1235 {
1236         DeleteHash((HashList**) FreeMe);
1237 }