740c0dd618a8ca61347514cd9bab4844ca4db3f6
[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(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 Set iterator object to point to key. If not found, don't change iterator
815  * @param Hash the list we reference
816  * @param HKey key to search for
817  * @param HKLen length of key
818  * @param At HashPos to update
819  * @return 0 if not found
820  */
821 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
822 {
823         long HashBinKey;
824         long HashAt;
825
826         if (Hash == NULL)
827                 return 0;
828
829         if (HKLen <= 0) {
830                 return  0;
831         }
832         /** first, find out were we could be... */
833         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
834         HashAt = FindInHash(Hash, HashBinKey);
835         if ((HashAt < 0) || /**< Not found at the lower edge? */
836             (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
837             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
838                 return 0;
839         }
840         /** GOTCHA! */
841         At->Position = HashAt;
842         return 1;
843 }
844
845 /**
846  * @ingroup HashListAccess
847  * @brief Delete from the Hash the entry at Position
848  * @param Hash the list we reference
849  * @param At the position within the Hash
850  * @return 0 if not found
851  */
852 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
853 {
854         Payload *FreeMe;
855         if (Hash == NULL)
856                 return 0;
857
858         /* if lockable, lock here */
859         if ((Hash == NULL) || 
860             (At->Position >= Hash->nLookupTableItems) || 
861             (At->Position < 0) ||
862             (At->Position > Hash->nLookupTableItems))
863         {
864                 /* unlock... */
865                 return 0;
866         }
867
868         FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
869         Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
870
871
872         /** delete our hashing data */
873         if (Hash->LookupTable[At->Position] != NULL)
874         {
875                 free(Hash->LookupTable[At->Position]->HashKey);
876                 free(Hash->LookupTable[At->Position]);
877                 if (At->Position < Hash->nLookupTableItems)
878                 {
879                         memmove(&Hash->LookupTable[At->Position],
880                                 &Hash->LookupTable[At->Position + 1],
881                                 (Hash->nLookupTableItems - At->Position - 1) * 
882                                 sizeof(HashKey*));
883
884                         Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
885                 }
886                 else 
887                         Hash->LookupTable[At->Position] = NULL;
888                 Hash->nLookupTableItems--;
889         }
890         /* unlock... */
891
892
893         /** get rid of our payload */
894         if (FreeMe != NULL)
895         {
896                 DeleteHashPayload(FreeMe);
897                 free(FreeMe);
898         }
899         return 1;
900 }
901
902 /**
903  * @ingroup HashListAccess
904  * @brief retrieve the counter from the itteratoor
905  * @param Hash which 
906  * @param At the Iterator to analyze
907  * @return the n'th hashposition we point at
908  */
909 int GetHashPosCounter(HashList *Hash, HashPos *At)
910 {
911         if ((Hash == NULL) || 
912             (At->Position >= Hash->nLookupTableItems) || 
913             (At->Position < 0) ||
914             (At->Position > Hash->nLookupTableItems))
915                 return 0;
916         return At->Position;
917 }
918
919 /**
920  * @ingroup HashListAccess
921  * @brief frees a linear hash iterator
922  */
923 void DeleteHashPos(HashPos **DelMe)
924 {
925         if (*DelMe != NULL)
926         {
927                 free(*DelMe);
928                 *DelMe = NULL;
929         }
930 }
931
932
933 /**
934  * @ingroup HashListAccess
935  * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
936  * @param Hash your Hashlist to follow
937  * @param At the position to retrieve the Item from and move forward afterwards
938  * @param HKLen returns Length of Hashkey Returned
939  * @param HashKey returns the Hashkey corrosponding to HashPos
940  * @param Data returns the Data found at HashPos
941  * @return whether the item was found or not.
942  */
943 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
944 {
945         long PayloadPos;
946
947         if ((Hash == NULL) || 
948             (At->Position >= Hash->nLookupTableItems) || 
949             (At->Position < 0) ||
950             (At->Position > Hash->nLookupTableItems))
951                 return 0;
952         *HKLen = Hash->LookupTable[At->Position]->HKLen;
953         *HashKey = Hash->LookupTable[At->Position]->HashKey;
954         PayloadPos = Hash->LookupTable[At->Position]->Position;
955         *Data = Hash->Members[PayloadPos]->Data;
956
957         /* Position is NULL-Based, while Stepwidth is not... */
958         if ((At->Position % abs(At->StepWidth)) == 0)
959                 At->Position += At->StepWidth;
960         else 
961                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
962                         (At->StepWidth / abs(At->StepWidth));
963         return 1;
964 }
965
966 /**
967  * @ingroup HashListAccess
968  * @brief Get the data located where HashPos Iterator points at
969  * @param Hash your Hashlist to follow
970  * @param At the position retrieve the data from
971  * @param HKLen returns Length of Hashkey Returned
972  * @param HashKey returns the Hashkey corrosponding to HashPos
973  * @param Data returns the Data found at HashPos
974  * @return whether the item was found or not.
975  */
976 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
977 {
978         long PayloadPos;
979
980         if ((Hash == NULL) || 
981             (At->Position >= Hash->nLookupTableItems) || 
982             (At->Position < 0) ||
983             (At->Position > Hash->nLookupTableItems))
984                 return 0;
985         *HKLen = Hash->LookupTable[At->Position]->HKLen;
986         *HashKey = Hash->LookupTable[At->Position]->HashKey;
987         PayloadPos = Hash->LookupTable[At->Position]->Position;
988         *Data = Hash->Members[PayloadPos]->Data;
989
990         return 1;
991 }
992
993 /**
994  * @ingroup HashListAccess
995  * @brief Move HashPos one forward
996  * @param Hash your Hashlist to follow
997  * @param At the position to move forward
998  * @return whether there is a next item or not.
999  */
1000 int NextHashPos(HashList *Hash, HashPos *At)
1001 {
1002         if ((Hash == NULL) || 
1003             (At->Position >= Hash->nLookupTableItems) || 
1004             (At->Position < 0) ||
1005             (At->Position > Hash->nLookupTableItems))
1006                 return 0;
1007
1008         /* Position is NULL-Based, while Stepwidth is not... */
1009         if ((At->Position % abs(At->StepWidth)) == 0)
1010                 At->Position += At->StepWidth;
1011         else 
1012                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
1013                         (At->StepWidth / abs(At->StepWidth));
1014         return !((At->Position >= Hash->nLookupTableItems) || 
1015                  (At->Position < 0) ||
1016                  (At->Position > Hash->nLookupTableItems));
1017 }
1018
1019 /**
1020  * @ingroup HashListAccess
1021  * @brief Get the data located where At points to
1022  * note: you should prefer iterator operations instead of using me.
1023  * @param Hash your Hashlist peek from
1024  * @param At get the item in the position At.
1025  * @param HKLen returns Length of Hashkey Returned
1026  * @param HashKey returns the Hashkey corrosponding to HashPos
1027  * @param Data returns the Data found at HashPos
1028  * @return whether the item was found or not.
1029  */
1030 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1031 {
1032         long PayloadPos;
1033
1034         if ((Hash == NULL) || 
1035             (At < 0) || 
1036             (At >= Hash->nLookupTableItems))
1037                 return 0;
1038         *HKLen = Hash->LookupTable[At]->HKLen;
1039         *HashKey = Hash->LookupTable[At]->HashKey;
1040         PayloadPos = Hash->LookupTable[At]->Position;
1041         *Data = Hash->Members[PayloadPos]->Data;
1042         return 1;
1043 }
1044
1045 /**
1046  * @ingroup HashListSort
1047  * @brief Get the data located where At points to
1048  * note: you should prefer iterator operations instead of using me.
1049  * @param Hash your Hashlist peek from
1050  * @param HKLen returns Length of Hashkey Returned
1051  * @param HashKey returns the Hashkey corrosponding to HashPos
1052  * @param Data returns the Data found at HashPos
1053  * @return whether the item was found or not.
1054  */
1055 /*
1056 long GetHashIDAt(HashList *Hash,long At)
1057 {
1058         if ((Hash == NULL) || 
1059             (At < 0) || 
1060             (At > Hash->nLookupTableItems))
1061                 return 0;
1062
1063         return Hash->LookupTable[At]->Key;
1064 }
1065 */
1066
1067
1068 /**
1069  * @ingroup HashListSort
1070  * @brief sorting function for sorting the Hash alphabeticaly by their strings
1071  * @param Key1 first item
1072  * @param Key2 second item
1073  */
1074 static int SortByKeys(const void *Key1, const void* Key2)
1075 {
1076         HashKey *HKey1, *HKey2;
1077         HKey1 = *(HashKey**) Key1;
1078         HKey2 = *(HashKey**) Key2;
1079
1080         return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1081 }
1082
1083 /**
1084  * @ingroup HashListSort
1085  * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1086  * @param Key1 first item
1087  * @param Key2 second item
1088  */
1089 static int SortByKeysRev(const void *Key1, const void* Key2)
1090 {
1091         HashKey *HKey1, *HKey2;
1092         HKey1 = *(HashKey**) Key1;
1093         HKey2 = *(HashKey**) Key2;
1094
1095         return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1096 }
1097
1098 /**
1099  * @ingroup HashListSort
1100  * @brief sorting function to regain hash-sequence and revert tainted status
1101  * @param Key1 first item
1102  * @param Key2 second item
1103  */
1104 static int SortByHashKeys(const void *Key1, const void* Key2)
1105 {
1106         HashKey *HKey1, *HKey2;
1107         HKey1 = *(HashKey**) Key1;
1108         HKey2 = *(HashKey**) Key2;
1109
1110         return HKey1->Key > HKey2->Key;
1111 }
1112
1113
1114 /**
1115  * @ingroup HashListSort
1116  * @brief sort the hash alphabeticaly by their keys.
1117  * Caution: This taints the hashlist, so accessing it later 
1118  * will be significantly slower! You can un-taint it by SortByHashKeyStr
1119  * @param Hash the list to sort
1120  * @param Order 0/1 Forward/Backward
1121  */
1122 void SortByHashKey(HashList *Hash, int Order)
1123 {
1124         if (Hash->nLookupTableItems < 2)
1125                 return;
1126         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), 
1127               (Order)?SortByKeys:SortByKeysRev);
1128         Hash->tainted = 1;
1129 }
1130
1131 /**
1132  * @ingroup HashListSort
1133  * @brief sort the hash by their keys (so it regains untainted state).
1134  * this will result in the sequence the hashing allgorithm produces it by default.
1135  * @param Hash the list to sort
1136  */
1137 void SortByHashKeyStr(HashList *Hash)
1138 {
1139         Hash->tainted = 0;
1140         if (Hash->nLookupTableItems < 2)
1141                 return;
1142         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1143 }
1144
1145
1146 /**
1147  * @ingroup HashListSort
1148  * @brief gives user sort routines access to the hash payload
1149  * @param HashVoid to retrieve Data to
1150  * @return Data belonging to HashVoid
1151  */
1152 const void *GetSearchPayload(const void *HashVoid)
1153 {
1154         return (*(HashKey**)HashVoid)->PL->Data;
1155 }
1156
1157 /**
1158  * @ingroup HashListSort
1159  * @brief sort the hash by your sort function. see the following sample.
1160  * this will result in the sequence the hashing allgorithm produces it by default.
1161  * @param Hash the list to sort
1162  * @param SortBy Sortfunction; see below how to implement this
1163  */
1164 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1165 {
1166         if (Hash->nLookupTableItems < 2)
1167                 return;
1168         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1169         Hash->tainted = 1;
1170 }
1171
1172
1173
1174
1175 /**
1176  * given you've put char * into your hash as a payload, a sort function might
1177  * look like this:
1178  * int SortByChar(const void* First, const void* Second)
1179  * {
1180  *      char *a, *b;
1181  *      a = (char*) GetSearchPayload(First);
1182  *      b = (char*) GetSearchPayload(Second);
1183  *      return strcmp (a, b);
1184  * }
1185  */
1186
1187
1188 /**
1189  * @ingroup HashListAccess
1190  * @brief Generic function to free a reference.  
1191  * since a reference actualy isn't needed to be freed, do nothing.
1192  */
1193 void reference_free_handler(void *ptr) 
1194 {
1195         return;
1196 }
1197
1198
1199 /**
1200  * @ingroup HashListAlgorithm
1201  * This exposes the hashlittle() function to consumers.
1202  */
1203 int HashLittle(const void *key, size_t length) {
1204         return (int)hashlittle(key, length, 1);
1205 }
1206
1207
1208 /**
1209  * @ingroup HashListMset
1210  * @brief parses an MSet string into a list for later use
1211  * @param MSetList List to be read from MSetStr
1212  * @param MSetStr String containing the list
1213  */
1214 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1215 {
1216         const char *POS = NULL, *SetPOS = NULL;
1217         StrBuf *OneSet;
1218         HashList *ThisMSet;
1219         long StartSet, EndSet;
1220         long *pEndSet;
1221         
1222         *MSetList = NULL;
1223         if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1224             return 0;
1225             
1226         OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1227         if (OneSet == NULL)
1228                 return 0;
1229
1230         ThisMSet = NewHash(0, lFlathash);
1231         if (ThisMSet == NULL)
1232         {
1233                 FreeStrBuf(&OneSet);
1234                 return 0;
1235         }
1236
1237         *MSetList = (MSet*) ThisMSet;
1238
1239         /* an MSet is a coma separated value list. */
1240         StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1241         do {
1242                 SetPOS = NULL;
1243
1244                 /* One set may consist of two Numbers: Start + optional End */
1245                 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1246                 EndSet = 0; /* no range is our default. */
1247                 /* do we have an end (aka range?) */
1248                 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1249                 {
1250                         if (*(SetPOS) == '*')
1251                                 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1252                         else 
1253                                 /* in other cases, get the EndPoint */
1254                                 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1255                 }
1256
1257                 pEndSet = (long*) malloc (sizeof(long));
1258                 if (pEndSet == NULL)
1259                 {
1260                         FreeStrBuf(&OneSet);
1261                         DeleteHash(&ThisMSet);
1262                         return 0;
1263                 }
1264                 *pEndSet = EndSet;
1265
1266                 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1267                 /* if we don't have another, we're done. */
1268                 if (POS == StrBufNOTNULL)
1269                         break;
1270                 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1271         } while (1);
1272         FreeStrBuf(&OneSet);
1273
1274         return 1;
1275 }
1276
1277 /**
1278  * @ingroup HashListMset
1279  * @brief checks whether a message is inside a mset
1280  * @param MSetList List to search for MsgNo
1281  * @param MsgNo number to search in mset
1282  */
1283 int IsInMSetList(MSet *MSetList, long MsgNo)
1284 {
1285         /* basicaly we are a ... */
1286         long MemberPosition;
1287         HashList *Hash = (HashList*) MSetList;
1288         long HashAt;
1289         long EndAt;
1290         long StartAt;
1291
1292         if (Hash == NULL)
1293                 return 0;
1294         if (Hash->MemberSize == 0)
1295                 return 0;
1296         /** first, find out were we could fit in... */
1297         HashAt = FindInHash(Hash, MsgNo);
1298         
1299         /* we're below the first entry, so not found. */
1300         if (HashAt < 0)
1301                 return 0;
1302         /* upper edge? move to last item */
1303         if (HashAt >= Hash->nMembersUsed)
1304                 HashAt = Hash->nMembersUsed - 1;
1305         /* Match? then we got it. */
1306         else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1307                 return 1;
1308         /* One above possible range start? we need to move to the lower one. */ 
1309         else if ((HashAt > 0) && 
1310                  (Hash->LookupTable[HashAt]->Key > MsgNo))
1311                 HashAt -=1;
1312
1313         /* Fetch the actual data */
1314         StartAt = Hash->LookupTable[HashAt]->Key;
1315         MemberPosition = Hash->LookupTable[HashAt]->Position;
1316         EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1317         if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1318                 return 1;
1319         /* no range? */
1320         if (EndAt == 0)
1321                 return 0;
1322         /* inside of range? */
1323         if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1324                 return 1;
1325         return 0;
1326 }
1327
1328
1329 /**
1330  * @ingroup HashListMset
1331  * @brief frees a mset [redirects to @ref DeleteHash
1332  * @param FreeMe to be free'd
1333  */
1334 void DeleteMSet(MSet **FreeMe)
1335 {
1336         DeleteHash((HashList**) FreeMe);
1337 }