2 * Copyright (c) 1987-2011 by the citadel.org team
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.
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.
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
25 #include "libcitadel.h"
28 typedef struct Payload Payload;
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.
39 * @defgroup HashListData Datastructures used for the internals of HashList
44 * @defgroup HashListDebug Hashlist debugging functions
49 * @defgroup HashListPrivate Hashlist internal functions
54 * @defgroup HashListSort Hashlist sorting functions
59 * @defgroup HashListAccess Hashlist functions to access / put / delete items in(to) the list
64 * @defgroup HashListAlgorithm functions to condense Key to an integer.
69 * @defgroup HashListMset MSet is sort of a derived hashlist, its special for treating Messagesets as Citadel uses them to store access rangesx
74 * @ingroup HashListData
75 * @brief Hash Payload storage Structure; filled in linear.
78 void *Data; /**< the Data belonging to this storage */
79 DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
84 * @ingroup HashListData
85 * @brief Hash key element; sorted by key
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 */
96 * @ingroup HashListData
97 * @brief Hash structure; holds arrays of Hashkey and Payload.
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? */
112 * @ingroup HashListData
113 * @brief Anonymous Hash Iterator Object. used for traversing the whole array from outside
116 long Position; /**< Position inside of the hash */
117 int StepWidth; /**< small? big? forward? backward? */
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
130 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
140 for (i=0; i < Hash->nLookupTableItems; i++) {
145 if (Hash->LookupTable[i - 1] == NULL)
148 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
150 if (Hash->LookupTable[i] == NULL) {
155 Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
156 KeyStr = Hash->LookupTable[i]->HashKey;
159 Trans(Previous, Next, i % 2);
160 PrintEntry(KeyStr, Next, i % 2);
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
174 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
179 const char *bla = "";
187 if (Hash->MyKeys != NULL)
190 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
192 printf("----------------------------------\n");
194 for (i=0; i < Hash->nLookupTableItems; i++) {
196 if (Hash->LookupTable[i] == NULL)
207 key = Hash->LookupTable[i]->Key;
208 foo = Hash->LookupTable[i]->HashKey;
214 First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
224 Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
233 if ((Hash->Algorithm == lFlathash) || (Hash->Algorithm == Flathash)) {
234 printf (" ---- Hashkey[%ld][%ld]: %ld '%s' Value: '%s' ; %s\n", i, key, *(long*) foo, foo, bar, bla);
237 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
242 printf("----------------------------------\n");
248 int TestValidateHash(HashList *TestHash)
252 if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
255 if (TestHash->nMembersUsed > TestHash->MemberSize)
258 for (i=0; i < TestHash->nMembersUsed; i++)
261 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
264 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
266 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
273 * @ingroup HashListAccess
274 * @brief instanciate a new hashlist
275 * @return the newly allocated list.
277 HashList *NewHash(int Uniq, HashFunc F)
280 NewList = malloc (sizeof(HashList));
283 memset(NewList, 0, sizeof(HashList));
285 NewList->Members = malloc(sizeof(Payload*) * 100);
286 if (NewList->Members == NULL)
291 memset(NewList->Members, 0, sizeof(Payload*) * 100);
293 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
294 if (NewList->LookupTable == NULL)
296 free(NewList->Members);
300 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
302 NewList->MemberSize = 100;
303 NewList->tainted = 0;
304 NewList->uniq = Uniq;
305 NewList->Algorithm = F;
310 int GetCount(HashList *Hash)
312 if(Hash==NULL) return 0;
313 return Hash->nLookupTableItems;
318 * @ingroup HashListPrivate
319 * @brief private destructor for one hash element.
320 * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
321 * @param Data an element to free using the user provided destructor, or just plain free
323 static void DeleteHashPayload (Payload *Data)
325 /** do we have a destructor for our payload? */
326 if (Data->Destructor)
327 Data->Destructor(Data->Data);
333 * @ingroup HashListPrivate
334 * @brief Destructor for nested hashes
336 void HDeleteHash(void *vHash)
338 HashList *FreeMe = (HashList*)vHash;
343 * @ingroup HashListAccess
344 * @brief flush the members of a hashlist
345 * Crashing? do 'print *FreeMe->LookupTable[i]'
346 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
348 void DeleteHashContent(HashList **Hash)
356 /* even if there are sparse members already deleted... */
357 for (i=0; i < FreeMe->nMembersUsed; i++)
359 /** get rid of our payload */
360 if (FreeMe->Members[i] != NULL)
362 DeleteHashPayload(FreeMe->Members[i]);
363 free(FreeMe->Members[i]);
365 /** delete our hashing data */
366 if (FreeMe->LookupTable[i] != NULL)
368 free(FreeMe->LookupTable[i]->HashKey);
369 free(FreeMe->LookupTable[i]);
372 FreeMe->nMembersUsed = 0;
374 FreeMe->nLookupTableItems = 0;
375 memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
376 memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
378 /** did s.b. want an array of our keys? free them. */
379 if (FreeMe->MyKeys != NULL)
380 free(FreeMe->MyKeys);
384 * @ingroup HashListAccess
385 * @brief destroy a hashlist and all of its members
386 * Crashing? do 'print *FreeMe->LookupTable[i]'
387 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
389 void DeleteHash(HashList **Hash)
396 DeleteHashContent(Hash);
397 /** now, free our arrays... */
398 free(FreeMe->LookupTable);
399 free(FreeMe->Members);
401 /** buye bye cruel world. */
407 * @ingroup HashListPrivate
408 * @brief Private function to increase the hash size.
409 * @param Hash the Hasharray to increase
411 static int IncreaseHashSize(HashList *Hash)
413 /* Ok, Our space is used up. Double the available space. */
414 Payload **NewPayloadArea;
420 /** If we grew to much, this might be the place to rehash and shrink again.
421 if ((Hash->NMembersUsed > Hash->nLookupTableItems) &&
422 ((Hash->NMembersUsed - Hash->nLookupTableItems) >
423 (Hash->nLookupTableItems / 10)))
430 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
431 if (NewPayloadArea == NULL)
433 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
434 if (NewTable == NULL)
436 free(NewPayloadArea);
440 /** double our payload area */
441 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
442 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
444 Hash->Members = NewPayloadArea;
446 /** double our hashtable area */
447 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
448 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
449 free(Hash->LookupTable);
450 Hash->LookupTable = NewTable;
452 Hash->MemberSize *= 2;
458 * @ingroup HashListPrivate
459 * @brief private function to add a new item to / replace an existing in - the hashlist
460 * if the hash list is full, its re-alloced with double size.
461 * @param Hash our hashlist to manipulate
462 * @param HashPos where should we insert / replace?
463 * @param HashKeyStr the Hash-String
464 * @param HKLen length of HashKeyStr
465 * @param Data your Payload to add
466 * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
468 static int InsertHashItem(HashList *Hash,
471 const char *HashKeyStr,
474 DeleteHashDataFunc Destructor)
476 Payload *NewPayloadItem;
483 if ((Hash->nMembersUsed >= Hash->MemberSize) &&
484 (!IncreaseHashSize (Hash)))
487 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
488 if (NewPayloadItem == NULL)
490 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
491 if (NewHashKey == NULL)
493 free(NewPayloadItem);
496 HashKeyOrgVal = (char *) malloc (HKLen + 1);
497 if (HashKeyOrgVal == NULL)
500 free(NewPayloadItem);
505 /** Arrange the payload */
506 NewPayloadItem->Data = Data;
507 NewPayloadItem->Destructor = Destructor;
508 /** Arrange the hashkey */
509 NewHashKey->HKLen = HKLen;
510 NewHashKey->HashKey = HashKeyOrgVal;
511 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
512 NewHashKey->Key = HashBinKey;
513 NewHashKey->PL = NewPayloadItem;
514 /** our payload is queued at the end... */
515 NewHashKey->Position = Hash->nMembersUsed;
516 /** but if we should be sorted into a specific place... */
517 if ((Hash->nLookupTableItems != 0) &&
518 (HashPos != Hash->nLookupTableItems) ) {
521 ItemsAfter = Hash->nLookupTableItems - HashPos;
522 /** make space were we can fill us in */
525 memmove(&Hash->LookupTable[HashPos + 1],
526 &Hash->LookupTable[HashPos],
527 ItemsAfter * sizeof(HashKey*));
531 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
532 Hash->LookupTable[HashPos] = NewHashKey;
533 Hash->nMembersUsed++;
534 Hash->nLookupTableItems++;
539 * @ingroup HashListSort
540 * @brief if the user has tainted the hash, but wants to insert / search items by their key
541 * we need to search linear through the array. You have been warned that this will take more time!
542 * @param Hash Our Hash to manipulate
543 * @param HashBinKey the Hash-Number to lookup.
544 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
546 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
553 for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
554 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
562 * @ingroup HashListPrivate
563 * @brief Private function to lookup the Item / the closest position to put it in
564 * @param Hash Our Hash to manipulate
565 * @param HashBinKey the Hash-Number to lookup.
566 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
568 static long FindInHash(HashList *Hash, long HashBinKey)
577 return FindInTaintedHash(Hash, HashBinKey);
579 SearchPos = Hash->nLookupTableItems / 2;
580 StepWidth = SearchPos / 2;
581 while ((SearchPos > 0) &&
582 (SearchPos < Hash->nLookupTableItems))
584 /** Did we find it? */
585 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
588 /** are we Aproximating in big steps? */
590 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
591 SearchPos -= StepWidth;
593 SearchPos += StepWidth;
596 else { /** We are right next to our target, within 4 positions */
597 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
598 if ((SearchPos > 0) &&
599 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
604 if ((SearchPos + 1 < Hash->nLookupTableItems) &&
605 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
617 * @ingroup HashListAlgorithm
618 * @brief another hashing algorithm; treat it as just a pointer to int.
619 * @param str Our pointer to the int value
620 * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
621 * @return the calculated hash value
623 long Flathash(const char *str, long len)
625 if (len != sizeof (int))
633 else return *(int*)str;
637 * @ingroup HashListAlgorithm
638 * @brief another hashing algorithm; treat it as just a pointer to long.
639 * @param str Our pointer to the long value
640 * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
641 * @return the calculated hash value
643 long lFlathash(const char *str, long len)
645 if (len != sizeof (long))
653 else return *(long*)str;
657 * @ingroup HashListPrivate
658 * @brief private abstract wrapper around the hashing algorithm
659 * @param HKey the hash string
660 * @param HKLen length of HKey
661 * @return the calculated hash value
663 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
668 if (Hash->Algorithm == NULL)
669 return hashlittle(HKey, HKLen, 9283457);
671 return Hash->Algorithm(HKey, HKLen);
676 * @ingroup HashListAccess
677 * @brief Add a new / Replace an existing item in the Hash
678 * @param Hash the list to manipulate
679 * @param HKey the hash-string to store Data under
680 * @param HKLen Length of HKey
681 * @param Data the payload you want to associate with HKey
682 * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
684 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
692 /** first, find out were we could fit in... */
693 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
694 HashAt = FindInHash(Hash, HashBinKey);
696 if ((HashAt >= Hash->MemberSize) &&
697 (!IncreaseHashSize (Hash)))
700 /** oh, we're brand new... */
701 if (Hash->LookupTable[HashAt] == NULL) {
702 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
703 }/** Insert Before? */
704 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
705 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
706 }/** Insert After? */
707 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
708 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
710 else { /** Ok, we have a colision. replace it. */
714 PayloadPos = Hash->LookupTable[HashAt]->Position;
715 DeleteHashPayload(Hash->Members[PayloadPos]);
716 Hash->Members[PayloadPos]->Data = Data;
717 Hash->Members[PayloadPos]->Destructor = DeleteIt;
720 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
726 * @ingroup HashListAccess
727 * @brief Lookup the Data associated with HKey
728 * @param Hash the Hashlist to search in
729 * @param HKey the hashkey to look up
730 * @param HKLen length of HKey
731 * @param Data returns the Data associated with HKey
732 * @return 0 if not found, 1 if.
734 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
746 /** first, find out were we could be... */
747 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
748 HashAt = FindInHash(Hash, HashBinKey);
749 if ((HashAt < 0) || /**< Not found at the lower edge? */
750 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
751 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
755 else { /** GOTCHA! */
758 MemberPosition = Hash->LookupTable[HashAt]->Position;
759 *Data = Hash->Members[MemberPosition]->Data;
765 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
771 * @ingroup HashListAccess
772 * @brief get the Keys present in this hash, similar to array_keys() in PHP
773 * Attention: List remains to Hash! don't modify or free it!
774 * @param Hash Your Hashlist to extract the keys from
775 * @param List returns the list of hashkeys stored in Hash
777 int GetHashKeys(HashList *Hash, char ***List)
784 if (Hash->MyKeys != NULL)
787 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
788 if (Hash->MyKeys == NULL)
791 for (i=0; i < Hash->nLookupTableItems; i++)
793 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
795 *List = (char**)Hash->MyKeys;
796 return Hash->nLookupTableItems;
800 * @ingroup HashListAccess
801 * @brief creates a hash-linear iterator object
802 * @param Hash the list we reference
803 * @param StepWidth in which step width should we iterate?
804 * If negative, the last position matching the
805 * step-raster is provided.
806 * @return the hash iterator
808 HashPos *GetNewHashPos(const HashList *Hash, int StepWidth)
812 Ret = (HashPos*)malloc(sizeof(HashPos));
817 Ret->StepWidth = StepWidth;
820 if (Ret->StepWidth < 0) {
821 Ret->Position = Hash->nLookupTableItems - 1;
830 * @ingroup HashListAccess
831 * @brief resets a hash-linear iterator object
832 * @param Hash the list we reference
833 * @param StepWidth in which step width should we iterate?
834 * @param it the iterator object to manipulate
835 * If negative, the last position matching the
836 * step-raster is provided.
837 * @return the hash iterator
839 void RewindHashPos(const HashList *Hash, HashPos *it, int StepWidth)
842 it->StepWidth = StepWidth;
845 if (it->StepWidth < 0) {
846 it->Position = Hash->nLookupTableItems - 1;
854 * @ingroup HashListAccess
855 * @brief Set iterator object to point to key. If not found, don't change iterator
856 * @param Hash the list we reference
857 * @param HKey key to search for
858 * @param HKLen length of key
859 * @param At HashPos to update
860 * @return 0 if not found
862 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
873 /** first, find out were we could be... */
874 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
875 HashAt = FindInHash(Hash, HashBinKey);
876 if ((HashAt < 0) || /**< Not found at the lower edge? */
877 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
878 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
882 At->Position = HashAt;
887 * @ingroup HashListAccess
888 * @brief Delete from the Hash the entry at Position
889 * @param Hash the list we reference
890 * @param At the position within the Hash
891 * @return 0 if not found
893 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
899 /* if lockable, lock here */
900 if ((Hash == NULL) ||
901 (At->Position >= Hash->nLookupTableItems) ||
902 (At->Position < 0) ||
903 (At->Position > Hash->nLookupTableItems))
909 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
910 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
913 /** delete our hashing data */
914 if (Hash->LookupTable[At->Position] != NULL)
916 free(Hash->LookupTable[At->Position]->HashKey);
917 free(Hash->LookupTable[At->Position]);
918 if (At->Position < Hash->nLookupTableItems)
920 memmove(&Hash->LookupTable[At->Position],
921 &Hash->LookupTable[At->Position + 1],
922 (Hash->nLookupTableItems - At->Position - 1) *
925 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
928 Hash->LookupTable[At->Position] = NULL;
929 Hash->nLookupTableItems--;
934 /** get rid of our payload */
937 DeleteHashPayload(FreeMe);
944 * @ingroup HashListAccess
945 * @brief retrieve the counter from the itteratoor
947 * @param At the Iterator to analyze
948 * @return the n'th hashposition we point at
950 int GetHashPosCounter(HashList *Hash, HashPos *At)
952 if ((Hash == NULL) ||
953 (At->Position >= Hash->nLookupTableItems) ||
954 (At->Position < 0) ||
955 (At->Position > Hash->nLookupTableItems))
961 * @ingroup HashListAccess
962 * @brief frees a linear hash iterator
964 void DeleteHashPos(HashPos **DelMe)
975 * @ingroup HashListAccess
976 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
977 * @param Hash your Hashlist to follow
978 * @param At the position to retrieve the Item from and move forward afterwards
979 * @param HKLen returns Length of Hashkey Returned
980 * @param HashKey returns the Hashkey corrosponding to HashPos
981 * @param Data returns the Data found at HashPos
982 * @return whether the item was found or not.
984 int GetNextHashPos(const HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
988 if ((Hash == NULL) ||
989 (At->Position >= Hash->nLookupTableItems) ||
990 (At->Position < 0) ||
991 (At->Position > Hash->nLookupTableItems))
993 *HKLen = Hash->LookupTable[At->Position]->HKLen;
994 *HashKey = Hash->LookupTable[At->Position]->HashKey;
995 PayloadPos = Hash->LookupTable[At->Position]->Position;
996 *Data = Hash->Members[PayloadPos]->Data;
998 /* Position is NULL-Based, while Stepwidth is not... */
999 if ((At->Position % abs(At->StepWidth)) == 0)
1000 At->Position += At->StepWidth;
1002 At->Position += ((At->Position) % abs(At->StepWidth)) *
1003 (At->StepWidth / abs(At->StepWidth));
1008 * @ingroup HashListAccess
1009 * @brief Get the data located where HashPos Iterator points at
1010 * @param Hash your Hashlist to follow
1011 * @param At the position retrieve the data from
1012 * @param HKLen returns Length of Hashkey Returned
1013 * @param HashKey returns the Hashkey corrosponding to HashPos
1014 * @param Data returns the Data found at HashPos
1015 * @return whether the item was found or not.
1017 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1021 if ((Hash == NULL) ||
1022 (At->Position >= Hash->nLookupTableItems) ||
1023 (At->Position < 0) ||
1024 (At->Position > Hash->nLookupTableItems))
1026 *HKLen = Hash->LookupTable[At->Position]->HKLen;
1027 *HashKey = Hash->LookupTable[At->Position]->HashKey;
1028 PayloadPos = Hash->LookupTable[At->Position]->Position;
1029 *Data = Hash->Members[PayloadPos]->Data;
1035 * @ingroup HashListAccess
1036 * @brief Move HashPos one forward
1037 * @param Hash your Hashlist to follow
1038 * @param At the position to move forward
1039 * @return whether there is a next item or not.
1041 int NextHashPos(HashList *Hash, HashPos *At)
1043 if ((Hash == NULL) ||
1044 (At->Position >= Hash->nLookupTableItems) ||
1045 (At->Position < 0) ||
1046 (At->Position > Hash->nLookupTableItems))
1049 /* Position is NULL-Based, while Stepwidth is not... */
1050 if ((At->Position % abs(At->StepWidth)) == 0)
1051 At->Position += At->StepWidth;
1053 At->Position += ((At->Position) % abs(At->StepWidth)) *
1054 (At->StepWidth / abs(At->StepWidth));
1055 return !((At->Position >= Hash->nLookupTableItems) ||
1056 (At->Position < 0) ||
1057 (At->Position > Hash->nLookupTableItems));
1061 * @ingroup HashListAccess
1062 * @brief Get the data located where At points to
1063 * note: you should prefer iterator operations instead of using me.
1064 * @param Hash your Hashlist peek from
1065 * @param At get the item in the position At.
1066 * @param HKLen returns Length of Hashkey Returned
1067 * @param HashKey returns the Hashkey corrosponding to HashPos
1068 * @param Data returns the Data found at HashPos
1069 * @return whether the item was found or not.
1071 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1075 if ((Hash == NULL) ||
1077 (At >= Hash->nLookupTableItems))
1079 *HKLen = Hash->LookupTable[At]->HKLen;
1080 *HashKey = Hash->LookupTable[At]->HashKey;
1081 PayloadPos = Hash->LookupTable[At]->Position;
1082 *Data = Hash->Members[PayloadPos]->Data;
1087 * @ingroup HashListSort
1088 * @brief Get the data located where At points to
1089 * note: you should prefer iterator operations instead of using me.
1090 * @param Hash your Hashlist peek from
1091 * @param HKLen returns Length of Hashkey Returned
1092 * @param HashKey returns the Hashkey corrosponding to HashPos
1093 * @param Data returns the Data found at HashPos
1094 * @return whether the item was found or not.
1097 long GetHashIDAt(HashList *Hash,long At)
1099 if ((Hash == NULL) ||
1101 (At > Hash->nLookupTableItems))
1104 return Hash->LookupTable[At]->Key;
1110 * @ingroup HashListSort
1111 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1112 * @param Key1 first item
1113 * @param Key2 second item
1115 static int SortByKeys(const void *Key1, const void* Key2)
1117 HashKey *HKey1, *HKey2;
1118 HKey1 = *(HashKey**) Key1;
1119 HKey2 = *(HashKey**) Key2;
1121 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1125 * @ingroup HashListSort
1126 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1127 * @param Key1 first item
1128 * @param Key2 second item
1130 static int SortByKeysRev(const void *Key1, const void* Key2)
1132 HashKey *HKey1, *HKey2;
1133 HKey1 = *(HashKey**) Key1;
1134 HKey2 = *(HashKey**) Key2;
1136 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1140 * @ingroup HashListSort
1141 * @brief sorting function to regain hash-sequence and revert tainted status
1142 * @param Key1 first item
1143 * @param Key2 second item
1145 static int SortByHashKeys(const void *Key1, const void* Key2)
1147 HashKey *HKey1, *HKey2;
1148 HKey1 = *(HashKey**) Key1;
1149 HKey2 = *(HashKey**) Key2;
1151 return HKey1->Key > HKey2->Key;
1156 * @ingroup HashListSort
1157 * @brief sort the hash alphabeticaly by their keys.
1158 * Caution: This taints the hashlist, so accessing it later
1159 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1160 * @param Hash the list to sort
1161 * @param Order 0/1 Forward/Backward
1163 void SortByHashKey(HashList *Hash, int Order)
1165 if (Hash->nLookupTableItems < 2)
1167 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1168 (Order)?SortByKeys:SortByKeysRev);
1173 * @ingroup HashListSort
1174 * @brief sort the hash by their keys (so it regains untainted state).
1175 * this will result in the sequence the hashing allgorithm produces it by default.
1176 * @param Hash the list to sort
1178 void SortByHashKeyStr(HashList *Hash)
1181 if (Hash->nLookupTableItems < 2)
1183 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1188 * @ingroup HashListSort
1189 * @brief gives user sort routines access to the hash payload
1190 * @param HashVoid to retrieve Data to
1191 * @return Data belonging to HashVoid
1193 const void *GetSearchPayload(const void *HashVoid)
1195 return (*(HashKey**)HashVoid)->PL->Data;
1199 * @ingroup HashListSort
1200 * @brief sort the hash by your sort function. see the following sample.
1201 * this will result in the sequence the hashing allgorithm produces it by default.
1202 * @param Hash the list to sort
1203 * @param SortBy Sortfunction; see below how to implement this
1205 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1207 if (Hash->nLookupTableItems < 2)
1209 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1217 * given you've put char * into your hash as a payload, a sort function might
1219 * int SortByChar(const void* First, const void* Second)
1222 * a = (char*) GetSearchPayload(First);
1223 * b = (char*) GetSearchPayload(Second);
1224 * return strcmp (a, b);
1230 * @ingroup HashListAccess
1231 * @brief Generic function to free a reference.
1232 * since a reference actualy isn't needed to be freed, do nothing.
1234 void reference_free_handler(void *ptr)
1241 * @ingroup HashListAlgorithm
1242 * This exposes the hashlittle() function to consumers.
1244 int HashLittle(const void *key, size_t length) {
1245 return (int)hashlittle(key, length, 1);
1250 * @ingroup HashListMset
1251 * @brief parses an MSet string into a list for later use
1252 * @param MSetList List to be read from MSetStr
1253 * @param MSetStr String containing the list
1255 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1257 const char *POS = NULL, *SetPOS = NULL;
1260 long StartSet, EndSet;
1264 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1267 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1271 ThisMSet = NewHash(0, lFlathash);
1272 if (ThisMSet == NULL)
1274 FreeStrBuf(&OneSet);
1278 *MSetList = (MSet*) ThisMSet;
1280 /* an MSet is a coma separated value list. */
1281 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1285 /* One set may consist of two Numbers: Start + optional End */
1286 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1287 EndSet = 0; /* no range is our default. */
1288 /* do we have an end (aka range?) */
1289 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1291 if (*(SetPOS) == '*')
1292 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1294 /* in other cases, get the EndPoint */
1295 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1298 pEndSet = (long*) malloc (sizeof(long));
1299 if (pEndSet == NULL)
1301 FreeStrBuf(&OneSet);
1302 DeleteHash(&ThisMSet);
1307 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1308 /* if we don't have another, we're done. */
1309 if (POS == StrBufNOTNULL)
1311 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1313 FreeStrBuf(&OneSet);
1319 * @ingroup HashListMset
1320 * @brief checks whether a message is inside a mset
1321 * @param MSetList List to search for MsgNo
1322 * @param MsgNo number to search in mset
1324 int IsInMSetList(MSet *MSetList, long MsgNo)
1326 /* basicaly we are a ... */
1327 long MemberPosition;
1328 HashList *Hash = (HashList*) MSetList;
1335 if (Hash->MemberSize == 0)
1337 /** first, find out were we could fit in... */
1338 HashAt = FindInHash(Hash, MsgNo);
1340 /* we're below the first entry, so not found. */
1343 /* upper edge? move to last item */
1344 if (HashAt >= Hash->nMembersUsed)
1345 HashAt = Hash->nMembersUsed - 1;
1346 /* Match? then we got it. */
1347 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1349 /* One above possible range start? we need to move to the lower one. */
1350 else if ((HashAt > 0) &&
1351 (Hash->LookupTable[HashAt]->Key > MsgNo))
1354 /* Fetch the actual data */
1355 StartAt = Hash->LookupTable[HashAt]->Key;
1356 MemberPosition = Hash->LookupTable[HashAt]->Position;
1357 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1358 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1363 /* inside of range? */
1364 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1371 * @ingroup HashListMset
1372 * @brief frees a mset [redirects to @ref DeleteHash
1373 * @param FreeMe to be free'd
1375 void DeleteMSet(MSet **FreeMe)
1377 DeleteHash((HashList**) FreeMe);