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 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
237 printf("----------------------------------\n");
243 int TestValidateHash(HashList *TestHash)
247 if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
250 if (TestHash->nMembersUsed > TestHash->MemberSize)
253 for (i=0; i < TestHash->nMembersUsed; i++)
256 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
259 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
261 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
268 * @ingroup HashListAccess
269 * @brief instanciate a new hashlist
270 * @return the newly allocated list.
272 HashList *NewHash(int Uniq, HashFunc F)
275 NewList = malloc (sizeof(HashList));
278 memset(NewList, 0, sizeof(HashList));
280 NewList->Members = malloc(sizeof(Payload*) * 100);
281 if (NewList->Members == NULL)
286 memset(NewList->Members, 0, sizeof(Payload*) * 100);
288 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
289 if (NewList->LookupTable == NULL)
291 free(NewList->Members);
295 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
297 NewList->MemberSize = 100;
298 NewList->tainted = 0;
299 NewList->uniq = Uniq;
300 NewList->Algorithm = F;
305 int GetCount(HashList *Hash)
307 if(Hash==NULL) return 0;
308 return Hash->nLookupTableItems;
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
318 static void DeleteHashPayload (Payload *Data)
320 /** do we have a destructor for our payload? */
321 if (Data->Destructor)
322 Data->Destructor(Data->Data);
328 * @ingroup HashListPrivate
329 * @brief Destructor for nested hashes
331 void HDeleteHash(void *vHash)
333 HashList *FreeMe = (HashList*)vHash;
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.
343 void DeleteHashContent(HashList **Hash)
351 /* even if there are sparse members already deleted... */
352 for (i=0; i < FreeMe->nMembersUsed; i++)
354 /** get rid of our payload */
355 if (FreeMe->Members[i] != NULL)
357 DeleteHashPayload(FreeMe->Members[i]);
358 free(FreeMe->Members[i]);
360 /** delete our hashing data */
361 if (FreeMe->LookupTable[i] != NULL)
363 free(FreeMe->LookupTable[i]->HashKey);
364 free(FreeMe->LookupTable[i]);
367 FreeMe->nMembersUsed = 0;
369 FreeMe->nLookupTableItems = 0;
370 memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
371 memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
373 /** did s.b. want an array of our keys? free them. */
374 if (FreeMe->MyKeys != NULL)
375 free(FreeMe->MyKeys);
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.
384 void DeleteHash(HashList **Hash)
391 DeleteHashContent(Hash);
392 /** now, free our arrays... */
393 free(FreeMe->LookupTable);
394 free(FreeMe->Members);
396 /** buye bye cruel world. */
402 * @ingroup HashListPrivate
403 * @brief Private function to increase the hash size.
404 * @param Hash the Hasharray to increase
406 static int IncreaseHashSize(HashList *Hash)
408 /* Ok, Our space is used up. Double the available space. */
409 Payload **NewPayloadArea;
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)))
425 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
426 if (NewPayloadArea == NULL)
428 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
429 if (NewTable == NULL)
431 free(NewPayloadArea);
435 /** double our payload area */
436 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
437 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
439 Hash->Members = NewPayloadArea;
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;
447 Hash->MemberSize *= 2;
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.
463 static int InsertHashItem(HashList *Hash,
466 const char *HashKeyStr,
469 DeleteHashDataFunc Destructor)
471 Payload *NewPayloadItem;
478 if ((Hash->nMembersUsed >= Hash->MemberSize) &&
479 (!IncreaseHashSize (Hash)))
482 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
483 if (NewPayloadItem == NULL)
485 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
486 if (NewHashKey == NULL)
488 free(NewPayloadItem);
491 HashKeyOrgVal = (char *) malloc (HKLen + 1);
492 if (HashKeyOrgVal == NULL)
495 free(NewPayloadItem);
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) ) {
516 ItemsAfter = Hash->nLookupTableItems - HashPos;
517 /** make space were we can fill us in */
520 memmove(&Hash->LookupTable[HashPos + 1],
521 &Hash->LookupTable[HashPos],
522 ItemsAfter * sizeof(HashKey*));
526 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
527 Hash->LookupTable[HashPos] = NewHashKey;
528 Hash->nMembersUsed++;
529 Hash->nLookupTableItems++;
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! )
541 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
548 for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
549 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
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! )
563 static long FindInHash(HashList *Hash, long HashBinKey)
572 return FindInTaintedHash(Hash, HashBinKey);
574 SearchPos = Hash->nLookupTableItems / 2;
575 StepWidth = SearchPos / 2;
576 while ((SearchPos > 0) &&
577 (SearchPos < Hash->nLookupTableItems))
579 /** Did we find it? */
580 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
583 /** are we Aproximating in big steps? */
585 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
586 SearchPos -= StepWidth;
588 SearchPos += StepWidth;
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))
599 if ((SearchPos + 1 < Hash->nLookupTableItems) &&
600 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
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
618 long Flathash(const char *str, long len)
620 if (len != sizeof (int))
622 else return *(int*)str;
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
632 long lFlathash(const char *str, long len)
634 if (len != sizeof (long))
636 else return *(long*)str;
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
646 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
651 if (Hash->Algorithm == NULL)
652 return hashlittle(HKey, HKLen, 9283457);
654 return Hash->Algorithm(HKey, HKLen);
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.
667 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
675 /** first, find out were we could fit in... */
676 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
677 HashAt = FindInHash(Hash, HashBinKey);
679 if ((HashAt >= Hash->MemberSize) &&
680 (!IncreaseHashSize (Hash)))
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);
693 else { /** Ok, we have a colision. replace it. */
697 PayloadPos = Hash->LookupTable[HashAt]->Position;
698 DeleteHashPayload(Hash->Members[PayloadPos]);
699 Hash->Members[PayloadPos]->Data = Data;
700 Hash->Members[PayloadPos]->Destructor = DeleteIt;
703 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
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.
717 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
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? */
738 else { /** GOTCHA! */
741 MemberPosition = Hash->LookupTable[HashAt]->Position;
742 *Data = Hash->Members[MemberPosition]->Data;
748 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
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
760 int GetHashKeys(HashList *Hash, char ***List)
767 if (Hash->MyKeys != NULL)
770 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
771 if (Hash->MyKeys == NULL)
774 for (i=0; i < Hash->nLookupTableItems; i++)
776 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
778 *List = (char**)Hash->MyKeys;
779 return Hash->nLookupTableItems;
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
791 HashPos *GetNewHashPos(const HashList *Hash, int StepWidth)
795 Ret = (HashPos*)malloc(sizeof(HashPos));
800 Ret->StepWidth = StepWidth;
803 if (Ret->StepWidth < 0) {
804 Ret->Position = Hash->nLookupTableItems - 1;
813 * @ingroup HashListAccess
814 * @brief resets a hash-linear iterator object
815 * @param Hash the list we reference
816 * @param StepWidth in which step width should we iterate?
817 * @param it the iterator object to manipulate
818 * If negative, the last position matching the
819 * step-raster is provided.
820 * @return the hash iterator
822 void RewindHashPos(const HashList *Hash, HashPos *it, int StepWidth)
825 it->StepWidth = StepWidth;
828 if (it->StepWidth < 0) {
829 it->Position = Hash->nLookupTableItems - 1;
837 * @ingroup HashListAccess
838 * @brief Set iterator object to point to key. If not found, don't change iterator
839 * @param Hash the list we reference
840 * @param HKey key to search for
841 * @param HKLen length of key
842 * @param At HashPos to update
843 * @return 0 if not found
845 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
856 /** first, find out were we could be... */
857 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
858 HashAt = FindInHash(Hash, HashBinKey);
859 if ((HashAt < 0) || /**< Not found at the lower edge? */
860 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
861 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
865 At->Position = HashAt;
870 * @ingroup HashListAccess
871 * @brief Delete from the Hash the entry at Position
872 * @param Hash the list we reference
873 * @param At the position within the Hash
874 * @return 0 if not found
876 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
882 /* if lockable, lock here */
883 if ((Hash == NULL) ||
884 (At->Position >= Hash->nLookupTableItems) ||
885 (At->Position < 0) ||
886 (At->Position > Hash->nLookupTableItems))
892 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
893 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
896 /** delete our hashing data */
897 if (Hash->LookupTable[At->Position] != NULL)
899 free(Hash->LookupTable[At->Position]->HashKey);
900 free(Hash->LookupTable[At->Position]);
901 if (At->Position < Hash->nLookupTableItems)
903 memmove(&Hash->LookupTable[At->Position],
904 &Hash->LookupTable[At->Position + 1],
905 (Hash->nLookupTableItems - At->Position - 1) *
908 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
911 Hash->LookupTable[At->Position] = NULL;
912 Hash->nLookupTableItems--;
917 /** get rid of our payload */
920 DeleteHashPayload(FreeMe);
927 * @ingroup HashListAccess
928 * @brief retrieve the counter from the itteratoor
930 * @param At the Iterator to analyze
931 * @return the n'th hashposition we point at
933 int GetHashPosCounter(HashList *Hash, HashPos *At)
935 if ((Hash == NULL) ||
936 (At->Position >= Hash->nLookupTableItems) ||
937 (At->Position < 0) ||
938 (At->Position > Hash->nLookupTableItems))
944 * @ingroup HashListAccess
945 * @brief frees a linear hash iterator
947 void DeleteHashPos(HashPos **DelMe)
958 * @ingroup HashListAccess
959 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
960 * @param Hash your Hashlist to follow
961 * @param At the position to retrieve the Item from and move forward afterwards
962 * @param HKLen returns Length of Hashkey Returned
963 * @param HashKey returns the Hashkey corrosponding to HashPos
964 * @param Data returns the Data found at HashPos
965 * @return whether the item was found or not.
967 int GetNextHashPos(const HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
971 if ((Hash == NULL) ||
972 (At->Position >= Hash->nLookupTableItems) ||
973 (At->Position < 0) ||
974 (At->Position > Hash->nLookupTableItems))
976 *HKLen = Hash->LookupTable[At->Position]->HKLen;
977 *HashKey = Hash->LookupTable[At->Position]->HashKey;
978 PayloadPos = Hash->LookupTable[At->Position]->Position;
979 *Data = Hash->Members[PayloadPos]->Data;
981 /* Position is NULL-Based, while Stepwidth is not... */
982 if ((At->Position % abs(At->StepWidth)) == 0)
983 At->Position += At->StepWidth;
985 At->Position += ((At->Position) % abs(At->StepWidth)) *
986 (At->StepWidth / abs(At->StepWidth));
991 * @ingroup HashListAccess
992 * @brief Get the data located where HashPos Iterator points at
993 * @param Hash your Hashlist to follow
994 * @param At the position retrieve the data from
995 * @param HKLen returns Length of Hashkey Returned
996 * @param HashKey returns the Hashkey corrosponding to HashPos
997 * @param Data returns the Data found at HashPos
998 * @return whether the item was found or not.
1000 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1004 if ((Hash == NULL) ||
1005 (At->Position >= Hash->nLookupTableItems) ||
1006 (At->Position < 0) ||
1007 (At->Position > Hash->nLookupTableItems))
1009 *HKLen = Hash->LookupTable[At->Position]->HKLen;
1010 *HashKey = Hash->LookupTable[At->Position]->HashKey;
1011 PayloadPos = Hash->LookupTable[At->Position]->Position;
1012 *Data = Hash->Members[PayloadPos]->Data;
1018 * @ingroup HashListAccess
1019 * @brief Move HashPos one forward
1020 * @param Hash your Hashlist to follow
1021 * @param At the position to move forward
1022 * @return whether there is a next item or not.
1024 int NextHashPos(HashList *Hash, HashPos *At)
1026 if ((Hash == NULL) ||
1027 (At->Position >= Hash->nLookupTableItems) ||
1028 (At->Position < 0) ||
1029 (At->Position > Hash->nLookupTableItems))
1032 /* Position is NULL-Based, while Stepwidth is not... */
1033 if ((At->Position % abs(At->StepWidth)) == 0)
1034 At->Position += At->StepWidth;
1036 At->Position += ((At->Position) % abs(At->StepWidth)) *
1037 (At->StepWidth / abs(At->StepWidth));
1038 return !((At->Position >= Hash->nLookupTableItems) ||
1039 (At->Position < 0) ||
1040 (At->Position > Hash->nLookupTableItems));
1044 * @ingroup HashListAccess
1045 * @brief Get the data located where At points to
1046 * note: you should prefer iterator operations instead of using me.
1047 * @param Hash your Hashlist peek from
1048 * @param At get the item in the position At.
1049 * @param HKLen returns Length of Hashkey Returned
1050 * @param HashKey returns the Hashkey corrosponding to HashPos
1051 * @param Data returns the Data found at HashPos
1052 * @return whether the item was found or not.
1054 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1058 if ((Hash == NULL) ||
1060 (At >= Hash->nLookupTableItems))
1062 *HKLen = Hash->LookupTable[At]->HKLen;
1063 *HashKey = Hash->LookupTable[At]->HashKey;
1064 PayloadPos = Hash->LookupTable[At]->Position;
1065 *Data = Hash->Members[PayloadPos]->Data;
1070 * @ingroup HashListSort
1071 * @brief Get the data located where At points to
1072 * note: you should prefer iterator operations instead of using me.
1073 * @param Hash your Hashlist peek from
1074 * @param HKLen returns Length of Hashkey Returned
1075 * @param HashKey returns the Hashkey corrosponding to HashPos
1076 * @param Data returns the Data found at HashPos
1077 * @return whether the item was found or not.
1080 long GetHashIDAt(HashList *Hash,long At)
1082 if ((Hash == NULL) ||
1084 (At > Hash->nLookupTableItems))
1087 return Hash->LookupTable[At]->Key;
1093 * @ingroup HashListSort
1094 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1095 * @param Key1 first item
1096 * @param Key2 second item
1098 static int SortByKeys(const void *Key1, const void* Key2)
1100 HashKey *HKey1, *HKey2;
1101 HKey1 = *(HashKey**) Key1;
1102 HKey2 = *(HashKey**) Key2;
1104 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1108 * @ingroup HashListSort
1109 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1110 * @param Key1 first item
1111 * @param Key2 second item
1113 static int SortByKeysRev(const void *Key1, const void* Key2)
1115 HashKey *HKey1, *HKey2;
1116 HKey1 = *(HashKey**) Key1;
1117 HKey2 = *(HashKey**) Key2;
1119 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1123 * @ingroup HashListSort
1124 * @brief sorting function to regain hash-sequence and revert tainted status
1125 * @param Key1 first item
1126 * @param Key2 second item
1128 static int SortByHashKeys(const void *Key1, const void* Key2)
1130 HashKey *HKey1, *HKey2;
1131 HKey1 = *(HashKey**) Key1;
1132 HKey2 = *(HashKey**) Key2;
1134 return HKey1->Key > HKey2->Key;
1139 * @ingroup HashListSort
1140 * @brief sort the hash alphabeticaly by their keys.
1141 * Caution: This taints the hashlist, so accessing it later
1142 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1143 * @param Hash the list to sort
1144 * @param Order 0/1 Forward/Backward
1146 void SortByHashKey(HashList *Hash, int Order)
1148 if (Hash->nLookupTableItems < 2)
1150 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1151 (Order)?SortByKeys:SortByKeysRev);
1156 * @ingroup HashListSort
1157 * @brief sort the hash by their keys (so it regains untainted state).
1158 * this will result in the sequence the hashing allgorithm produces it by default.
1159 * @param Hash the list to sort
1161 void SortByHashKeyStr(HashList *Hash)
1164 if (Hash->nLookupTableItems < 2)
1166 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1171 * @ingroup HashListSort
1172 * @brief gives user sort routines access to the hash payload
1173 * @param HashVoid to retrieve Data to
1174 * @return Data belonging to HashVoid
1176 const void *GetSearchPayload(const void *HashVoid)
1178 return (*(HashKey**)HashVoid)->PL->Data;
1182 * @ingroup HashListSort
1183 * @brief sort the hash by your sort function. see the following sample.
1184 * this will result in the sequence the hashing allgorithm produces it by default.
1185 * @param Hash the list to sort
1186 * @param SortBy Sortfunction; see below how to implement this
1188 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1190 if (Hash->nLookupTableItems < 2)
1192 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1200 * given you've put char * into your hash as a payload, a sort function might
1202 * int SortByChar(const void* First, const void* Second)
1205 * a = (char*) GetSearchPayload(First);
1206 * b = (char*) GetSearchPayload(Second);
1207 * return strcmp (a, b);
1213 * @ingroup HashListAccess
1214 * @brief Generic function to free a reference.
1215 * since a reference actualy isn't needed to be freed, do nothing.
1217 void reference_free_handler(void *ptr)
1224 * @ingroup HashListAlgorithm
1225 * This exposes the hashlittle() function to consumers.
1227 int HashLittle(const void *key, size_t length) {
1228 return (int)hashlittle(key, length, 1);
1233 * @ingroup HashListMset
1234 * @brief parses an MSet string into a list for later use
1235 * @param MSetList List to be read from MSetStr
1236 * @param MSetStr String containing the list
1238 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1240 const char *POS = NULL, *SetPOS = NULL;
1243 long StartSet, EndSet;
1247 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1250 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1254 ThisMSet = NewHash(0, lFlathash);
1255 if (ThisMSet == NULL)
1257 FreeStrBuf(&OneSet);
1261 *MSetList = (MSet*) ThisMSet;
1263 /* an MSet is a coma separated value list. */
1264 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1268 /* One set may consist of two Numbers: Start + optional End */
1269 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1270 EndSet = 0; /* no range is our default. */
1271 /* do we have an end (aka range?) */
1272 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1274 if (*(SetPOS) == '*')
1275 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1277 /* in other cases, get the EndPoint */
1278 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1281 pEndSet = (long*) malloc (sizeof(long));
1282 if (pEndSet == NULL)
1284 FreeStrBuf(&OneSet);
1285 DeleteHash(&ThisMSet);
1290 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1291 /* if we don't have another, we're done. */
1292 if (POS == StrBufNOTNULL)
1294 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1296 FreeStrBuf(&OneSet);
1302 * @ingroup HashListMset
1303 * @brief checks whether a message is inside a mset
1304 * @param MSetList List to search for MsgNo
1305 * @param MsgNo number to search in mset
1307 int IsInMSetList(MSet *MSetList, long MsgNo)
1309 /* basicaly we are a ... */
1310 long MemberPosition;
1311 HashList *Hash = (HashList*) MSetList;
1318 if (Hash->MemberSize == 0)
1320 /** first, find out were we could fit in... */
1321 HashAt = FindInHash(Hash, MsgNo);
1323 /* we're below the first entry, so not found. */
1326 /* upper edge? move to last item */
1327 if (HashAt >= Hash->nMembersUsed)
1328 HashAt = Hash->nMembersUsed - 1;
1329 /* Match? then we got it. */
1330 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1332 /* One above possible range start? we need to move to the lower one. */
1333 else if ((HashAt > 0) &&
1334 (Hash->LookupTable[HashAt]->Key > MsgNo))
1337 /* Fetch the actual data */
1338 StartAt = Hash->LookupTable[HashAt]->Key;
1339 MemberPosition = Hash->LookupTable[HashAt]->Position;
1340 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1341 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1346 /* inside of range? */
1347 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1354 * @ingroup HashListMset
1355 * @brief frees a mset [redirects to @ref DeleteHash
1356 * @param FreeMe to be free'd
1358 void DeleteMSet(MSet **FreeMe)
1360 DeleteHash((HashList**) FreeMe);