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