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