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