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)
178 const char *bla = "";
185 if (Hash->MyKeys != NULL)
188 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
190 printf("----------------------------------\n");
192 for (i=0; i < Hash->nLookupTableItems; i++) {
194 if (Hash->LookupTable[i] == NULL)
202 key = Hash->LookupTable[i]->Key;
203 foo = Hash->LookupTable[i]->HashKey;
205 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
209 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
214 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
218 printf("----------------------------------\n");
224 int TestValidateHash(HashList *TestHash)
228 if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
231 if (TestHash->nMembersUsed > TestHash->MemberSize)
234 for (i=0; i < TestHash->nMembersUsed; i++)
237 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
240 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
242 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
249 * @ingroup HashListAccess
250 * @brief instanciate a new hashlist
251 * @return the newly allocated list.
253 HashList *NewHash(int Uniq, HashFunc F)
256 NewList = malloc (sizeof(HashList));
257 memset(NewList, 0, sizeof(HashList));
259 NewList->Members = malloc(sizeof(Payload*) * 100);
260 memset(NewList->Members, 0, sizeof(Payload*) * 100);
262 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
263 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
265 NewList->MemberSize = 100;
266 NewList->tainted = 0;
267 NewList->uniq = Uniq;
268 NewList->Algorithm = F;
273 int GetCount(HashList *Hash)
275 if(Hash==NULL) return 0;
276 return Hash->nLookupTableItems;
281 * @ingroup HashListPrivate
282 * @brief private destructor for one hash element.
283 * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
284 * @param Data an element to free using the user provided destructor, or just plain free
286 static void DeleteHashPayload (Payload *Data)
288 /** do we have a destructor for our payload? */
289 if (Data->Destructor)
290 Data->Destructor(Data->Data);
296 * @ingroup HashListPrivate
297 * @brief Destructor for nested hashes
299 void HDeleteHash(void *vHash)
301 HashList *FreeMe = (HashList*)vHash;
306 * @ingroup HashListAccess
307 * @brief flush the members of a hashlist
308 * Crashing? do 'print *FreeMe->LookupTable[i]'
309 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
311 void DeleteHashContent(HashList **Hash)
319 /* even if there are sparse members already deleted... */
320 for (i=0; i < FreeMe->nMembersUsed; i++)
322 /** get rid of our payload */
323 if (FreeMe->Members[i] != NULL)
325 DeleteHashPayload(FreeMe->Members[i]);
326 free(FreeMe->Members[i]);
328 /** delete our hashing data */
329 if (FreeMe->LookupTable[i] != NULL)
331 free(FreeMe->LookupTable[i]->HashKey);
332 free(FreeMe->LookupTable[i]);
335 FreeMe->nMembersUsed = 0;
337 FreeMe->nLookupTableItems = 0;
338 memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
339 memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
341 /** did s.b. want an array of our keys? free them. */
342 if (FreeMe->MyKeys != NULL)
343 free(FreeMe->MyKeys);
347 * @ingroup HashListAccess
348 * @brief destroy a hashlist and all of its members
349 * Crashing? do 'print *FreeMe->LookupTable[i]'
350 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
352 void DeleteHash(HashList **Hash)
359 DeleteHashContent(Hash);
360 /** now, free our arrays... */
361 free(FreeMe->LookupTable);
362 free(FreeMe->Members);
364 /** buye bye cruel world. */
370 * @ingroup HashListPrivate
371 * @brief Private function to increase the hash size.
372 * @param Hash the Hasharray to increase
374 static void IncreaseHashSize(HashList *Hash)
376 /* Ok, Our space is used up. Double the available space. */
377 Payload **NewPayloadArea;
383 /** If we grew to much, this might be the place to rehash and shrink again.
384 if ((Hash->NMembersUsed > Hash->nLookupTableItems) &&
385 ((Hash->NMembersUsed - Hash->nLookupTableItems) >
386 (Hash->nLookupTableItems / 10)))
393 /** double our payload area */
394 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
395 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
396 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
398 Hash->Members = NewPayloadArea;
400 /** double our hashtable area */
401 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
402 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
403 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
404 free(Hash->LookupTable);
405 Hash->LookupTable = NewTable;
407 Hash->MemberSize *= 2;
412 * @ingroup HashListPrivate
413 * @brief private function to add a new item to / replace an existing in - the hashlist
414 * if the hash list is full, its re-alloced with double size.
415 * @param Hash our hashlist to manipulate
416 * @param HashPos where should we insert / replace?
417 * @param HashKeyStr the Hash-String
418 * @param HKLen length of HashKeyStr
419 * @param Data your Payload to add
420 * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
422 static void InsertHashItem(HashList *Hash,
425 const char *HashKeyStr,
428 DeleteHashDataFunc Destructor)
430 Payload *NewPayloadItem;
436 if (Hash->nMembersUsed >= Hash->MemberSize)
437 IncreaseHashSize (Hash);
439 /** Arrange the payload */
440 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
441 NewPayloadItem->Data = Data;
442 NewPayloadItem->Destructor = Destructor;
443 /** Arrange the hashkey */
444 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
445 NewHashKey->HashKey = (char *) malloc (HKLen + 1);
446 NewHashKey->HKLen = HKLen;
447 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
448 NewHashKey->Key = HashBinKey;
449 NewHashKey->PL = NewPayloadItem;
450 /** our payload is queued at the end... */
451 NewHashKey->Position = Hash->nMembersUsed;
452 /** but if we should be sorted into a specific place... */
453 if ((Hash->nLookupTableItems != 0) &&
454 (HashPos != Hash->nLookupTableItems) ) {
457 ItemsAfter = Hash->nLookupTableItems - HashPos;
458 /** make space were we can fill us in */
461 memmove(&Hash->LookupTable[HashPos + 1],
462 &Hash->LookupTable[HashPos],
463 ItemsAfter * sizeof(HashKey*));
467 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
468 Hash->LookupTable[HashPos] = NewHashKey;
469 Hash->nMembersUsed++;
470 Hash->nLookupTableItems++;
474 * @ingroup HashListSort
475 * @brief if the user has tainted the hash, but wants to insert / search items by their key
476 * we need to search linear through the array. You have been warned that this will take more time!
477 * @param Hash Our Hash to manipulate
478 * @param HashBinKey the Hash-Number to lookup.
479 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
481 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
488 for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
489 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
497 * @ingroup HashListPrivate
498 * @brief Private function to lookup the Item / the closest position to put it in
499 * @param Hash Our Hash to manipulate
500 * @param HashBinKey the Hash-Number to lookup.
501 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
503 static long FindInHash(HashList *Hash, long HashBinKey)
512 return FindInTaintedHash(Hash, HashBinKey);
514 SearchPos = Hash->nLookupTableItems / 2;
515 StepWidth = SearchPos / 2;
516 while ((SearchPos > 0) &&
517 (SearchPos < Hash->nLookupTableItems))
519 /** Did we find it? */
520 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
523 /** are we Aproximating in big steps? */
525 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
526 SearchPos -= StepWidth;
528 SearchPos += StepWidth;
531 else { /** We are right next to our target, within 4 positions */
532 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
533 if ((SearchPos > 0) &&
534 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
539 if ((SearchPos + 1 < Hash->nLookupTableItems) &&
540 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
552 * @ingroup HashListAlgorithm
553 * @brief another hashing algorithm; treat it as just a pointer to int.
554 * @param str Our pointer to the int value
555 * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
556 * @return the calculated hash value
558 long Flathash(const char *str, long len)
560 if (len != sizeof (int))
562 else return *(int*)str;
566 * @ingroup HashListAlgorithm
567 * @brief another hashing algorithm; treat it as just a pointer to long.
568 * @param str Our pointer to the long value
569 * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
570 * @return the calculated hash value
572 long lFlathash(const char *str, long len)
574 if (len != sizeof (long))
576 else return *(long*)str;
580 * @ingroup HashListPrivate
581 * @brief private abstract wrapper around the hashing algorithm
582 * @param HKey the hash string
583 * @param HKLen length of HKey
584 * @return the calculated hash value
586 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
591 if (Hash->Algorithm == NULL)
592 return hashlittle(HKey, HKLen, 9283457);
594 return Hash->Algorithm(HKey, HKLen);
599 * @ingroup HashListAccess
600 * @brief Add a new / Replace an existing item in the Hash
601 * @param Hash the list to manipulate
602 * @param HKey the hash-string to store Data under
603 * @param HKLen Length of HKey
604 * @param Data the payload you want to associate with HKey
605 * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
607 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
615 /** first, find out were we could fit in... */
616 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
617 HashAt = FindInHash(Hash, HashBinKey);
619 if (HashAt >= Hash->MemberSize)
620 IncreaseHashSize (Hash);
622 /** oh, we're brand new... */
623 if (Hash->LookupTable[HashAt] == NULL) {
624 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
625 }/** Insert Before? */
626 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
627 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
628 }/** Insert After? */
629 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
630 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
632 else { /** Ok, we have a colision. replace it. */
636 PayloadPos = Hash->LookupTable[HashAt]->Position;
637 DeleteHashPayload(Hash->Members[PayloadPos]);
638 Hash->Members[PayloadPos]->Data = Data;
639 Hash->Members[PayloadPos]->Destructor = DeleteIt;
642 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
648 * @ingroup HashListAccess
649 * @brief Lookup the Data associated with HKey
650 * @param Hash the Hashlist to search in
651 * @param HKey the hashkey to look up
652 * @param HKLen length of HKey
653 * @param Data returns the Data associated with HKey
654 * @return 0 if not found, 1 if.
656 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
668 /** first, find out were we could be... */
669 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
670 HashAt = FindInHash(Hash, HashBinKey);
671 if ((HashAt < 0) || /**< Not found at the lower edge? */
672 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
673 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
677 else { /** GOTCHA! */
680 MemberPosition = Hash->LookupTable[HashAt]->Position;
681 *Data = Hash->Members[MemberPosition]->Data;
687 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
693 * @ingroup HashListAccess
694 * @brief get the Keys present in this hash, simila to array_keys() in PHP
695 * Attention: List remains to Hash! don't modify or free it!
696 * @param Hash Your Hashlist to extract the keys from
697 * @param List returns the list of hashkeys stored in Hash
699 int GetHashKeys(HashList *Hash, char ***List)
704 if (Hash->MyKeys != NULL)
707 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
708 for (i=0; i < Hash->nLookupTableItems; i++) {
710 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
712 *List = (char**)Hash->MyKeys;
713 return Hash->nLookupTableItems;
717 * @ingroup HashListAccess
718 * @brief creates a hash-linear iterator object
719 * @param Hash the list we reference
720 * @param StepWidth in which step width should we iterate?
721 * If negative, the last position matching the
722 * step-raster is provided.
723 * @return the hash iterator
725 HashPos *GetNewHashPos(HashList *Hash, int StepWidth)
729 Ret = (HashPos*)malloc(sizeof(HashPos));
731 Ret->StepWidth = StepWidth;
734 if (Ret->StepWidth < 0) {
735 Ret->Position = Hash->nLookupTableItems - 1;
744 * @ingroup HashListAccess
745 * @brief Set iterator object to point to key. If not found, don't change iterator
746 * @param Hash the list we reference
747 * @param HKey key to search for
748 * @param HKLen length of key
749 * @param At HashPos to update
750 * @return 0 if not found
752 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
763 /** first, find out were we could be... */
764 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
765 HashAt = FindInHash(Hash, HashBinKey);
766 if ((HashAt < 0) || /**< Not found at the lower edge? */
767 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
768 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
772 At->Position = HashAt;
777 * @ingroup HashListAccess
778 * @brief Delete from the Hash the entry at Position
779 * @param Hash the list we reference
780 * @param At the position within the Hash
781 * @return 0 if not found
783 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
789 /* if lockable, lock here */
790 if ((Hash == NULL) ||
791 (At->Position >= Hash->nLookupTableItems) ||
792 (At->Position < 0) ||
793 (At->Position > Hash->nLookupTableItems))
799 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
800 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
803 /** delete our hashing data */
804 if (Hash->LookupTable[At->Position] != NULL)
806 free(Hash->LookupTable[At->Position]->HashKey);
807 free(Hash->LookupTable[At->Position]);
808 if (At->Position < Hash->nLookupTableItems)
810 memmove(&Hash->LookupTable[At->Position],
811 &Hash->LookupTable[At->Position + 1],
812 (Hash->nLookupTableItems - At->Position - 1) *
815 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
818 Hash->LookupTable[At->Position] = NULL;
819 Hash->nLookupTableItems--;
824 /** get rid of our payload */
827 DeleteHashPayload(FreeMe);
834 * @ingroup HashListAccess
835 * @brief retrieve the counter from the itteratoor
837 * @param At the Iterator to analyze
838 * @return the n'th hashposition we point at
840 int GetHashPosCounter(HashList *Hash, HashPos *At)
842 if ((Hash == NULL) ||
843 (At->Position >= Hash->nLookupTableItems) ||
844 (At->Position < 0) ||
845 (At->Position > Hash->nLookupTableItems))
851 * @ingroup HashListAccess
852 * @brief frees a linear hash iterator
854 void DeleteHashPos(HashPos **DelMe)
865 * @ingroup HashListAccess
866 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
867 * @param Hash your Hashlist to follow
868 * @param At the position to retrieve the Item from and move forward afterwards
869 * @param HKLen returns Length of Hashkey Returned
870 * @param HashKey returns the Hashkey corrosponding to HashPos
871 * @param Data returns the Data found at HashPos
872 * @return whether the item was found or not.
874 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
878 if ((Hash == NULL) ||
879 (At->Position >= Hash->nLookupTableItems) ||
880 (At->Position < 0) ||
881 (At->Position > Hash->nLookupTableItems))
883 *HKLen = Hash->LookupTable[At->Position]->HKLen;
884 *HashKey = Hash->LookupTable[At->Position]->HashKey;
885 PayloadPos = Hash->LookupTable[At->Position]->Position;
886 *Data = Hash->Members[PayloadPos]->Data;
888 /* Position is NULL-Based, while Stepwidth is not... */
889 if ((At->Position % abs(At->StepWidth)) == 0)
890 At->Position += At->StepWidth;
892 At->Position += ((At->Position) % abs(At->StepWidth)) *
893 (At->StepWidth / abs(At->StepWidth));
898 * @ingroup HashListAccess
899 * @brief Get the data located where HashPos Iterator points at
900 * @param Hash your Hashlist to follow
901 * @param At the position retrieve the data from
902 * @param HKLen returns Length of Hashkey Returned
903 * @param HashKey returns the Hashkey corrosponding to HashPos
904 * @param Data returns the Data found at HashPos
905 * @return whether the item was found or not.
907 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
911 if ((Hash == NULL) ||
912 (At->Position >= Hash->nLookupTableItems) ||
913 (At->Position < 0) ||
914 (At->Position > Hash->nLookupTableItems))
916 *HKLen = Hash->LookupTable[At->Position]->HKLen;
917 *HashKey = Hash->LookupTable[At->Position]->HashKey;
918 PayloadPos = Hash->LookupTable[At->Position]->Position;
919 *Data = Hash->Members[PayloadPos]->Data;
925 * @ingroup HashListAccess
926 * @brief Move HashPos one forward
927 * @param Hash your Hashlist to follow
928 * @param At the position to move forward
929 * @return whether there is a next item or not.
931 int NextHashPos(HashList *Hash, HashPos *At)
933 if ((Hash == NULL) ||
934 (At->Position >= Hash->nLookupTableItems) ||
935 (At->Position < 0) ||
936 (At->Position > Hash->nLookupTableItems))
939 /* Position is NULL-Based, while Stepwidth is not... */
940 if ((At->Position % abs(At->StepWidth)) == 0)
941 At->Position += At->StepWidth;
943 At->Position += ((At->Position) % abs(At->StepWidth)) *
944 (At->StepWidth / abs(At->StepWidth));
945 return !((At->Position >= Hash->nLookupTableItems) ||
946 (At->Position < 0) ||
947 (At->Position > Hash->nLookupTableItems));
951 * @ingroup HashListAccess
952 * @brief Get the data located where At points to
953 * note: you should prefer iterator operations instead of using me.
954 * @param Hash your Hashlist peek from
955 * @param At get the item in the position At.
956 * @param HKLen returns Length of Hashkey Returned
957 * @param HashKey returns the Hashkey corrosponding to HashPos
958 * @param Data returns the Data found at HashPos
959 * @return whether the item was found or not.
961 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
965 if ((Hash == NULL) ||
967 (At >= Hash->nLookupTableItems))
969 *HKLen = Hash->LookupTable[At]->HKLen;
970 *HashKey = Hash->LookupTable[At]->HashKey;
971 PayloadPos = Hash->LookupTable[At]->Position;
972 *Data = Hash->Members[PayloadPos]->Data;
977 * @ingroup HashListSort
978 * @brief Get the data located where At points to
979 * note: you should prefer iterator operations instead of using me.
980 * @param Hash your Hashlist peek from
981 * @param HKLen returns Length of Hashkey Returned
982 * @param HashKey returns the Hashkey corrosponding to HashPos
983 * @param Data returns the Data found at HashPos
984 * @return whether the item was found or not.
987 long GetHashIDAt(HashList *Hash,long At)
989 if ((Hash == NULL) ||
991 (At > Hash->nLookupTableItems))
994 return Hash->LookupTable[At]->Key;
1000 * @ingroup HashListSort
1001 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1002 * @param Key1 first item
1003 * @param Key2 second item
1005 static int SortByKeys(const void *Key1, const void* Key2)
1007 HashKey *HKey1, *HKey2;
1008 HKey1 = *(HashKey**) Key1;
1009 HKey2 = *(HashKey**) Key2;
1011 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1015 * @ingroup HashListSort
1016 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1017 * @param Key1 first item
1018 * @param Key2 second item
1020 static int SortByKeysRev(const void *Key1, const void* Key2)
1022 HashKey *HKey1, *HKey2;
1023 HKey1 = *(HashKey**) Key1;
1024 HKey2 = *(HashKey**) Key2;
1026 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1030 * @ingroup HashListSort
1031 * @brief sorting function to regain hash-sequence and revert tainted status
1032 * @param Key1 first item
1033 * @param Key2 second item
1035 static int SortByHashKeys(const void *Key1, const void* Key2)
1037 HashKey *HKey1, *HKey2;
1038 HKey1 = *(HashKey**) Key1;
1039 HKey2 = *(HashKey**) Key2;
1041 return HKey1->Key > HKey2->Key;
1046 * @ingroup HashListSort
1047 * @brief sort the hash alphabeticaly by their keys.
1048 * Caution: This taints the hashlist, so accessing it later
1049 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1050 * @param Hash the list to sort
1051 * @param Order 0/1 Forward/Backward
1053 void SortByHashKey(HashList *Hash, int Order)
1055 if (Hash->nLookupTableItems < 2)
1057 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1058 (Order)?SortByKeys:SortByKeysRev);
1063 * @ingroup HashListSort
1064 * @brief sort the hash by their keys (so it regains untainted state).
1065 * this will result in the sequence the hashing allgorithm produces it by default.
1066 * @param Hash the list to sort
1068 void SortByHashKeyStr(HashList *Hash)
1071 if (Hash->nLookupTableItems < 2)
1073 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1078 * @ingroup HashListSort
1079 * @brief gives user sort routines access to the hash payload
1080 * @param HashVoid to retrieve Data to
1081 * @return Data belonging to HashVoid
1083 const void *GetSearchPayload(const void *HashVoid)
1085 return (*(HashKey**)HashVoid)->PL->Data;
1089 * @ingroup HashListSort
1090 * @brief sort the hash by your sort function. see the following sample.
1091 * this will result in the sequence the hashing allgorithm produces it by default.
1092 * @param Hash the list to sort
1093 * @param SortBy Sortfunction; see below how to implement this
1095 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1097 if (Hash->nLookupTableItems < 2)
1099 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1107 * given you've put char * into your hash as a payload, a sort function might
1109 * int SortByChar(const void* First, const void* Second)
1112 * a = (char*) GetSearchPayload(First);
1113 * b = (char*) GetSearchPayload(Second);
1114 * return strcmp (a, b);
1120 * @ingroup HashListAccess
1121 * @brief Generic function to free a reference.
1122 * since a reference actualy isn't needed to be freed, do nothing.
1124 void reference_free_handler(void *ptr)
1131 * @ingroup HashListAlgorithm
1132 * This exposes the hashlittle() function to consumers.
1134 int HashLittle(const void *key, size_t length) {
1135 return (int)hashlittle(key, length, 1);
1140 * @ingroup HashListMset
1141 * @brief parses an MSet string into a list for later use
1142 * @param MSetList List to be read from MSetStr
1143 * @param MSetStr String containing the list
1145 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1147 const char *POS = NULL, *SetPOS = NULL;
1150 long StartSet, EndSet;
1154 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1157 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1159 ThisMSet = NewHash(0, lFlathash);
1161 *MSetList = (MSet*) ThisMSet;
1163 /* an MSet is a coma separated value list. */
1164 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1168 /* One set may consist of two Numbers: Start + optional End */
1169 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1170 EndSet = 0; /* no range is our default. */
1171 /* do we have an end (aka range?) */
1172 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1174 if (*(SetPOS) == '*')
1175 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1177 /* in other cases, get the EndPoint */
1178 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1181 pEndSet = (long*) malloc (sizeof(long));
1184 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1185 /* if we don't have another, we're done. */
1186 if (POS == StrBufNOTNULL)
1188 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1190 FreeStrBuf(&OneSet);
1196 * @ingroup HashListMset
1197 * @brief checks whether a message is inside a mset
1198 * @param MSetList List to search for MsgNo
1199 * @param MsgNo number to search in mset
1201 int IsInMSetList(MSet *MSetList, long MsgNo)
1203 /* basicaly we are a ... */
1204 long MemberPosition;
1205 HashList *Hash = (HashList*) MSetList;
1212 if (Hash->MemberSize == 0)
1214 /** first, find out were we could fit in... */
1215 HashAt = FindInHash(Hash, MsgNo);
1217 /* we're below the first entry, so not found. */
1220 /* upper edge? move to last item */
1221 if (HashAt >= Hash->nMembersUsed)
1222 HashAt = Hash->nMembersUsed - 1;
1223 /* Match? then we got it. */
1224 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1226 /* One above possible range start? we need to move to the lower one. */
1227 else if ((HashAt > 0) &&
1228 (Hash->LookupTable[HashAt]->Key > MsgNo))
1231 /* Fetch the actual data */
1232 StartAt = Hash->LookupTable[HashAt]->Key;
1233 MemberPosition = Hash->LookupTable[HashAt]->Position;
1234 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1235 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1240 /* inside of range? */
1241 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1248 * @ingroup HashListMset
1249 * @brief frees a mset [redirects to @ref DeleteHash
1250 * @param FreeMe to be free'd
1252 void DeleteMSet(MSet **FreeMe)
1254 DeleteHash((HashList**) FreeMe);