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