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