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