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