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);
165 const char *dbg_PrintStrBufPayload(const char *Key, void *Item, int Odd)
167 return ChrPtr((StrBuf*)Item);
171 * @ingroup HashListDebug
172 * @brief verify the contents of a hash list; here for debugging purposes.
173 * @param Hash your Hashlist structure
174 * @param First Functionpointer to allow you to print your payload
175 * @param Second Functionpointer to allow you to print your payload
178 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
183 const char *bla = "";
191 if (Hash->MyKeys != NULL)
194 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
196 printf("----------------------------------\n");
198 for (i=0; i < Hash->nLookupTableItems; i++) {
200 if (Hash->LookupTable[i] == NULL)
211 key = Hash->LookupTable[i]->Key;
212 foo = Hash->LookupTable[i]->HashKey;
218 First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
228 Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
237 if ((Hash->Algorithm == lFlathash) || (Hash->Algorithm == Flathash)) {
238 printf (" ---- Hashkey[%ld][%ld]: %ld '%s' Value: '%s' ; %s\n", i, key, *(long*) foo, foo, bar, bla);
241 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
246 printf("----------------------------------\n");
252 int TestValidateHash(HashList *TestHash)
256 if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
259 if (TestHash->nMembersUsed > TestHash->MemberSize)
262 for (i=0; i < TestHash->nMembersUsed; i++)
265 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
268 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
270 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
277 * @ingroup HashListAccess
278 * @brief instanciate a new hashlist
279 * @return the newly allocated list.
281 HashList *NewHash(int Uniq, HashFunc F)
284 NewList = malloc (sizeof(HashList));
287 memset(NewList, 0, sizeof(HashList));
289 NewList->Members = malloc(sizeof(Payload*) * 100);
290 if (NewList->Members == NULL)
295 memset(NewList->Members, 0, sizeof(Payload*) * 100);
297 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
298 if (NewList->LookupTable == NULL)
300 free(NewList->Members);
304 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
306 NewList->MemberSize = 100;
307 NewList->tainted = 0;
308 NewList->uniq = Uniq;
309 NewList->Algorithm = F;
314 int GetCount(HashList *Hash)
316 if(Hash==NULL) return 0;
317 return Hash->nLookupTableItems;
322 * @ingroup HashListPrivate
323 * @brief private destructor for one hash element.
324 * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
325 * @param Data an element to free using the user provided destructor, or just plain free
327 static void DeleteHashPayload (Payload *Data)
329 /** do we have a destructor for our payload? */
330 if (Data->Destructor)
331 Data->Destructor(Data->Data);
337 * @ingroup HashListPrivate
338 * @brief Destructor for nested hashes
340 void HDeleteHash(void *vHash)
342 HashList *FreeMe = (HashList*)vHash;
347 * @ingroup HashListAccess
348 * @brief flush the members of a hashlist
349 * Crashing? do 'print *FreeMe->LookupTable[i]'
350 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
352 void DeleteHashContent(HashList **Hash)
360 /* even if there are sparse members already deleted... */
361 for (i=0; i < FreeMe->nMembersUsed; i++)
363 /** get rid of our payload */
364 if (FreeMe->Members[i] != NULL)
366 DeleteHashPayload(FreeMe->Members[i]);
367 free(FreeMe->Members[i]);
369 /** delete our hashing data */
370 if (FreeMe->LookupTable[i] != NULL)
372 free(FreeMe->LookupTable[i]->HashKey);
373 free(FreeMe->LookupTable[i]);
376 FreeMe->nMembersUsed = 0;
378 FreeMe->nLookupTableItems = 0;
379 memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
380 memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
382 /** did s.b. want an array of our keys? free them. */
383 if (FreeMe->MyKeys != NULL)
384 free(FreeMe->MyKeys);
388 * @ingroup HashListAccess
389 * @brief destroy a hashlist and all of its members
390 * Crashing? do 'print *FreeMe->LookupTable[i]'
391 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
393 void DeleteHash(HashList **Hash)
400 DeleteHashContent(Hash);
401 /** now, free our arrays... */
402 free(FreeMe->LookupTable);
403 free(FreeMe->Members);
405 /** buye bye cruel world. */
411 * @ingroup HashListPrivate
412 * @brief Private function to increase the hash size.
413 * @param Hash the Hasharray to increase
415 static int IncreaseHashSize(HashList *Hash)
417 /* Ok, Our space is used up. Double the available space. */
418 Payload **NewPayloadArea;
424 /** If we grew to much, this might be the place to rehash and shrink again.
425 if ((Hash->NMembersUsed > Hash->nLookupTableItems) &&
426 ((Hash->NMembersUsed - Hash->nLookupTableItems) >
427 (Hash->nLookupTableItems / 10)))
434 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
435 if (NewPayloadArea == NULL)
437 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
438 if (NewTable == NULL)
440 free(NewPayloadArea);
444 /** double our payload area */
445 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
446 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
448 Hash->Members = NewPayloadArea;
450 /** double our hashtable area */
451 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
452 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
453 free(Hash->LookupTable);
454 Hash->LookupTable = NewTable;
456 Hash->MemberSize *= 2;
462 * @ingroup HashListPrivate
463 * @brief private function to add a new item to / replace an existing in - the hashlist
464 * if the hash list is full, its re-alloced with double size.
465 * @param Hash our hashlist to manipulate
466 * @param HashPos where should we insert / replace?
467 * @param HashKeyStr the Hash-String
468 * @param HKLen length of HashKeyStr
469 * @param Data your Payload to add
470 * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
472 static int InsertHashItem(HashList *Hash,
475 const char *HashKeyStr,
478 DeleteHashDataFunc Destructor)
480 Payload *NewPayloadItem;
487 if ((Hash->nMembersUsed >= Hash->MemberSize) &&
488 (!IncreaseHashSize (Hash)))
491 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
492 if (NewPayloadItem == NULL)
494 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
495 if (NewHashKey == NULL)
497 free(NewPayloadItem);
500 HashKeyOrgVal = (char *) malloc (HKLen + 1);
501 if (HashKeyOrgVal == NULL)
504 free(NewPayloadItem);
509 /** Arrange the payload */
510 NewPayloadItem->Data = Data;
511 NewPayloadItem->Destructor = Destructor;
512 /** Arrange the hashkey */
513 NewHashKey->HKLen = HKLen;
514 NewHashKey->HashKey = HashKeyOrgVal;
515 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
516 NewHashKey->Key = HashBinKey;
517 NewHashKey->PL = NewPayloadItem;
518 /** our payload is queued at the end... */
519 NewHashKey->Position = Hash->nMembersUsed;
520 /** but if we should be sorted into a specific place... */
521 if ((Hash->nLookupTableItems != 0) &&
522 (HashPos != Hash->nLookupTableItems) ) {
525 ItemsAfter = Hash->nLookupTableItems - HashPos;
526 /** make space were we can fill us in */
529 memmove(&Hash->LookupTable[HashPos + 1],
530 &Hash->LookupTable[HashPos],
531 ItemsAfter * sizeof(HashKey*));
535 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
536 Hash->LookupTable[HashPos] = NewHashKey;
537 Hash->nMembersUsed++;
538 Hash->nLookupTableItems++;
543 * @ingroup HashListSort
544 * @brief if the user has tainted the hash, but wants to insert / search items by their key
545 * we need to search linear through the array. You have been warned that this will take more time!
546 * @param Hash Our Hash to manipulate
547 * @param HashBinKey the Hash-Number to lookup.
548 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
550 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
557 for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
558 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
566 * @ingroup HashListPrivate
567 * @brief Private function to lookup the Item / the closest position to put it in
568 * @param Hash Our Hash to manipulate
569 * @param HashBinKey the Hash-Number to lookup.
570 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
572 static long FindInHash(HashList *Hash, long HashBinKey)
581 return FindInTaintedHash(Hash, HashBinKey);
583 SearchPos = Hash->nLookupTableItems / 2;
584 StepWidth = SearchPos / 2;
585 while ((SearchPos > 0) &&
586 (SearchPos < Hash->nLookupTableItems))
588 /** Did we find it? */
589 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
592 /** are we Aproximating in big steps? */
594 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
595 SearchPos -= StepWidth;
597 SearchPos += StepWidth;
600 else { /** We are right next to our target, within 4 positions */
601 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
602 if ((SearchPos > 0) &&
603 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
608 if ((SearchPos + 1 < Hash->nLookupTableItems) &&
609 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
621 * @ingroup HashListAlgorithm
622 * @brief another hashing algorithm; treat it as just a pointer to int.
623 * @param str Our pointer to the int value
624 * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
625 * @return the calculated hash value
627 long Flathash(const char *str, long len)
629 if (len != sizeof (int))
637 else return *(int*)str;
641 * @ingroup HashListAlgorithm
642 * @brief another hashing algorithm; treat it as just a pointer to long.
643 * @param str Our pointer to the long value
644 * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
645 * @return the calculated hash value
647 long lFlathash(const char *str, long len)
649 if (len != sizeof (long))
657 else return *(long*)str;
661 * @ingroup HashListPrivate
662 * @brief private abstract wrapper around the hashing algorithm
663 * @param HKey the hash string
664 * @param HKLen length of HKey
665 * @return the calculated hash value
667 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
672 if (Hash->Algorithm == NULL)
673 return hashlittle(HKey, HKLen, 9283457);
675 return Hash->Algorithm(HKey, HKLen);
680 * @ingroup HashListAccess
681 * @brief Add a new / Replace an existing item in the Hash
682 * @param Hash the list to manipulate
683 * @param HKey the hash-string to store Data under
684 * @param HKLen Length of HKey
685 * @param Data the payload you want to associate with HKey
686 * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
688 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
696 /** first, find out were we could fit in... */
697 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
698 HashAt = FindInHash(Hash, HashBinKey);
700 if ((HashAt >= Hash->MemberSize) &&
701 (!IncreaseHashSize (Hash)))
704 /** oh, we're brand new... */
705 if (Hash->LookupTable[HashAt] == NULL) {
706 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
707 }/** Insert Before? */
708 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
709 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
710 }/** Insert After? */
711 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
712 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
714 else { /** Ok, we have a colision. replace it. */
718 PayloadPos = Hash->LookupTable[HashAt]->Position;
719 DeleteHashPayload(Hash->Members[PayloadPos]);
720 Hash->Members[PayloadPos]->Data = Data;
721 Hash->Members[PayloadPos]->Destructor = DeleteIt;
724 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
730 * @ingroup HashListAccess
731 * @brief Lookup the Data associated with HKey
732 * @param Hash the Hashlist to search in
733 * @param HKey the hashkey to look up
734 * @param HKLen length of HKey
735 * @param Data returns the Data associated with HKey
736 * @return 0 if not found, 1 if.
738 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
750 /** first, find out were we could be... */
751 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
752 HashAt = FindInHash(Hash, HashBinKey);
753 if ((HashAt < 0) || /**< Not found at the lower edge? */
754 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
755 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
759 else { /** GOTCHA! */
762 MemberPosition = Hash->LookupTable[HashAt]->Position;
763 *Data = Hash->Members[MemberPosition]->Data;
769 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
775 * @ingroup HashListAccess
776 * @brief get the Keys present in this hash, similar to array_keys() in PHP
777 * Attention: List remains to Hash! don't modify or free it!
778 * @param Hash Your Hashlist to extract the keys from
779 * @param List returns the list of hashkeys stored in Hash
781 int GetHashKeys(HashList *Hash, char ***List)
788 if (Hash->MyKeys != NULL)
791 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
792 if (Hash->MyKeys == NULL)
795 for (i=0; i < Hash->nLookupTableItems; i++)
797 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
799 *List = (char**)Hash->MyKeys;
800 return Hash->nLookupTableItems;
804 * @ingroup HashListAccess
805 * @brief creates a hash-linear iterator object
806 * @param Hash the list we reference
807 * @param StepWidth in which step width should we iterate?
808 * If negative, the last position matching the
809 * step-raster is provided.
810 * @return the hash iterator
812 HashPos *GetNewHashPos(const HashList *Hash, int StepWidth)
816 Ret = (HashPos*)malloc(sizeof(HashPos));
821 Ret->StepWidth = StepWidth;
824 if (Ret->StepWidth < 0) {
825 Ret->Position = Hash->nLookupTableItems - 1;
834 * @ingroup HashListAccess
835 * @brief resets a hash-linear iterator object
836 * @param Hash the list we reference
837 * @param StepWidth in which step width should we iterate?
838 * @param it the iterator object to manipulate
839 * If negative, the last position matching the
840 * step-raster is provided.
841 * @return the hash iterator
843 void RewindHashPos(const HashList *Hash, HashPos *it, int StepWidth)
846 it->StepWidth = StepWidth;
849 if (it->StepWidth < 0) {
850 it->Position = Hash->nLookupTableItems - 1;
858 * @ingroup HashListAccess
859 * @brief Set iterator object to point to key. If not found, don't change iterator
860 * @param Hash the list we reference
861 * @param HKey key to search for
862 * @param HKLen length of key
863 * @param At HashPos to update
864 * @return 0 if not found
866 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
877 /** first, find out were we could be... */
878 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
879 HashAt = FindInHash(Hash, HashBinKey);
880 if ((HashAt < 0) || /**< Not found at the lower edge? */
881 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
882 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
886 At->Position = HashAt;
891 * @ingroup HashListAccess
892 * @brief Delete from the Hash the entry at Position
893 * @param Hash the list we reference
894 * @param At the position within the Hash
895 * @return 0 if not found
897 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
903 /* if lockable, lock here */
904 if ((Hash == NULL) ||
905 (At->Position >= Hash->nLookupTableItems) ||
906 (At->Position < 0) ||
907 (At->Position > Hash->nLookupTableItems))
913 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
914 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
917 /** delete our hashing data */
918 if (Hash->LookupTable[At->Position] != NULL)
920 free(Hash->LookupTable[At->Position]->HashKey);
921 free(Hash->LookupTable[At->Position]);
922 if (At->Position < Hash->nLookupTableItems)
924 memmove(&Hash->LookupTable[At->Position],
925 &Hash->LookupTable[At->Position + 1],
926 (Hash->nLookupTableItems - At->Position - 1) *
929 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
932 Hash->LookupTable[At->Position] = NULL;
933 Hash->nLookupTableItems--;
938 /** get rid of our payload */
941 DeleteHashPayload(FreeMe);
948 * @ingroup HashListAccess
949 * @brief retrieve the counter from the itteratoor
951 * @param At the Iterator to analyze
952 * @return the n'th hashposition we point at
954 int GetHashPosCounter(HashList *Hash, HashPos *At)
956 if ((Hash == NULL) ||
957 (At->Position >= Hash->nLookupTableItems) ||
958 (At->Position < 0) ||
959 (At->Position > Hash->nLookupTableItems))
965 * @ingroup HashListAccess
966 * @brief frees a linear hash iterator
968 void DeleteHashPos(HashPos **DelMe)
979 * @ingroup HashListAccess
980 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
981 * @param Hash your Hashlist to follow
982 * @param At the position to retrieve the Item from and move forward afterwards
983 * @param HKLen returns Length of Hashkey Returned
984 * @param HashKey returns the Hashkey corrosponding to HashPos
985 * @param Data returns the Data found at HashPos
986 * @return whether the item was found or not.
988 int GetNextHashPos(const HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
992 if ((Hash == NULL) ||
993 (At->Position >= Hash->nLookupTableItems) ||
994 (At->Position < 0) ||
995 (At->Position > Hash->nLookupTableItems))
997 *HKLen = Hash->LookupTable[At->Position]->HKLen;
998 *HashKey = Hash->LookupTable[At->Position]->HashKey;
999 PayloadPos = Hash->LookupTable[At->Position]->Position;
1000 *Data = Hash->Members[PayloadPos]->Data;
1002 /* Position is NULL-Based, while Stepwidth is not... */
1003 if ((At->Position % abs(At->StepWidth)) == 0)
1004 At->Position += At->StepWidth;
1006 At->Position += ((At->Position) % abs(At->StepWidth)) *
1007 (At->StepWidth / abs(At->StepWidth));
1012 * @ingroup HashListAccess
1013 * @brief Get the data located where HashPos Iterator points at
1014 * @param Hash your Hashlist to follow
1015 * @param At the position retrieve the data from
1016 * @param HKLen returns Length of Hashkey Returned
1017 * @param HashKey returns the Hashkey corrosponding to HashPos
1018 * @param Data returns the Data found at HashPos
1019 * @return whether the item was found or not.
1021 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1025 if ((Hash == NULL) ||
1026 (At->Position >= Hash->nLookupTableItems) ||
1027 (At->Position < 0) ||
1028 (At->Position > Hash->nLookupTableItems))
1030 *HKLen = Hash->LookupTable[At->Position]->HKLen;
1031 *HashKey = Hash->LookupTable[At->Position]->HashKey;
1032 PayloadPos = Hash->LookupTable[At->Position]->Position;
1033 *Data = Hash->Members[PayloadPos]->Data;
1039 * @ingroup HashListAccess
1040 * @brief Move HashPos one forward
1041 * @param Hash your Hashlist to follow
1042 * @param At the position to move forward
1043 * @return whether there is a next item or not.
1045 int NextHashPos(HashList *Hash, HashPos *At)
1047 if ((Hash == NULL) ||
1048 (At->Position >= Hash->nLookupTableItems) ||
1049 (At->Position < 0) ||
1050 (At->Position > Hash->nLookupTableItems))
1053 /* Position is NULL-Based, while Stepwidth is not... */
1054 if ((At->Position % abs(At->StepWidth)) == 0)
1055 At->Position += At->StepWidth;
1057 At->Position += ((At->Position) % abs(At->StepWidth)) *
1058 (At->StepWidth / abs(At->StepWidth));
1059 return !((At->Position >= Hash->nLookupTableItems) ||
1060 (At->Position < 0) ||
1061 (At->Position > Hash->nLookupTableItems));
1065 * @ingroup HashListAccess
1066 * @brief Get the data located where At points to
1067 * note: you should prefer iterator operations instead of using me.
1068 * @param Hash your Hashlist peek from
1069 * @param At get the item in the position At.
1070 * @param HKLen returns Length of Hashkey Returned
1071 * @param HashKey returns the Hashkey corrosponding to HashPos
1072 * @param Data returns the Data found at HashPos
1073 * @return whether the item was found or not.
1075 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1079 if ((Hash == NULL) ||
1081 (At >= Hash->nLookupTableItems))
1083 *HKLen = Hash->LookupTable[At]->HKLen;
1084 *HashKey = Hash->LookupTable[At]->HashKey;
1085 PayloadPos = Hash->LookupTable[At]->Position;
1086 *Data = Hash->Members[PayloadPos]->Data;
1091 * @ingroup HashListSort
1092 * @brief Get the data located where At points to
1093 * note: you should prefer iterator operations instead of using me.
1094 * @param Hash your Hashlist peek from
1095 * @param HKLen returns Length of Hashkey Returned
1096 * @param HashKey returns the Hashkey corrosponding to HashPos
1097 * @param Data returns the Data found at HashPos
1098 * @return whether the item was found or not.
1101 long GetHashIDAt(HashList *Hash,long At)
1103 if ((Hash == NULL) ||
1105 (At > Hash->nLookupTableItems))
1108 return Hash->LookupTable[At]->Key;
1114 * @ingroup HashListSort
1115 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1116 * @param Key1 first item
1117 * @param Key2 second item
1119 static int SortByKeys(const void *Key1, const void* Key2)
1121 HashKey *HKey1, *HKey2;
1122 HKey1 = *(HashKey**) Key1;
1123 HKey2 = *(HashKey**) Key2;
1125 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1129 * @ingroup HashListSort
1130 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1131 * @param Key1 first item
1132 * @param Key2 second item
1134 static int SortByKeysRev(const void *Key1, const void* Key2)
1136 HashKey *HKey1, *HKey2;
1137 HKey1 = *(HashKey**) Key1;
1138 HKey2 = *(HashKey**) Key2;
1140 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1144 * @ingroup HashListSort
1145 * @brief sorting function to regain hash-sequence and revert tainted status
1146 * @param Key1 first item
1147 * @param Key2 second item
1149 static int SortByHashKeys(const void *Key1, const void* Key2)
1151 HashKey *HKey1, *HKey2;
1152 HKey1 = *(HashKey**) Key1;
1153 HKey2 = *(HashKey**) Key2;
1155 return HKey1->Key > HKey2->Key;
1160 * @ingroup HashListSort
1161 * @brief sort the hash alphabeticaly by their keys.
1162 * Caution: This taints the hashlist, so accessing it later
1163 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1164 * @param Hash the list to sort
1165 * @param Order 0/1 Forward/Backward
1167 void SortByHashKey(HashList *Hash, int Order)
1169 if (Hash->nLookupTableItems < 2)
1171 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1172 (Order)?SortByKeys:SortByKeysRev);
1177 * @ingroup HashListSort
1178 * @brief sort the hash by their keys (so it regains untainted state).
1179 * this will result in the sequence the hashing allgorithm produces it by default.
1180 * @param Hash the list to sort
1182 void SortByHashKeyStr(HashList *Hash)
1185 if (Hash->nLookupTableItems < 2)
1187 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1192 * @ingroup HashListSort
1193 * @brief gives user sort routines access to the hash payload
1194 * @param HashVoid to retrieve Data to
1195 * @return Data belonging to HashVoid
1197 const void *GetSearchPayload(const void *HashVoid)
1199 return (*(HashKey**)HashVoid)->PL->Data;
1203 * @ingroup HashListSort
1204 * @brief sort the hash by your sort function. see the following sample.
1205 * this will result in the sequence the hashing allgorithm produces it by default.
1206 * @param Hash the list to sort
1207 * @param SortBy Sortfunction; see below how to implement this
1209 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1211 if (Hash->nLookupTableItems < 2)
1213 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1221 * given you've put char * into your hash as a payload, a sort function might
1223 * int SortByChar(const void* First, const void* Second)
1226 * a = (char*) GetSearchPayload(First);
1227 * b = (char*) GetSearchPayload(Second);
1228 * return strcmp (a, b);
1234 * @ingroup HashListAccess
1235 * @brief Generic function to free a reference.
1236 * since a reference actualy isn't needed to be freed, do nothing.
1238 void reference_free_handler(void *ptr)
1245 * @ingroup HashListAlgorithm
1246 * This exposes the hashlittle() function to consumers.
1248 int HashLittle(const void *key, size_t length) {
1249 return (int)hashlittle(key, length, 1);
1254 * @ingroup HashListMset
1255 * @brief parses an MSet string into a list for later use
1256 * @param MSetList List to be read from MSetStr
1257 * @param MSetStr String containing the list
1259 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1261 const char *POS = NULL, *SetPOS = NULL;
1264 long StartSet, EndSet;
1268 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1271 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1275 ThisMSet = NewHash(0, lFlathash);
1276 if (ThisMSet == NULL)
1278 FreeStrBuf(&OneSet);
1282 *MSetList = (MSet*) ThisMSet;
1284 /* an MSet is a coma separated value list. */
1285 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1289 /* One set may consist of two Numbers: Start + optional End */
1290 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1291 EndSet = 0; /* no range is our default. */
1292 /* do we have an end (aka range?) */
1293 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1295 if (*(SetPOS) == '*')
1296 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1298 /* in other cases, get the EndPoint */
1299 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1302 pEndSet = (long*) malloc (sizeof(long));
1303 if (pEndSet == NULL)
1305 FreeStrBuf(&OneSet);
1306 DeleteHash(&ThisMSet);
1311 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1312 /* if we don't have another, we're done. */
1313 if (POS == StrBufNOTNULL)
1315 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1317 FreeStrBuf(&OneSet);
1323 * @ingroup HashListMset
1324 * @brief checks whether a message is inside a mset
1325 * @param MSetList List to search for MsgNo
1326 * @param MsgNo number to search in mset
1328 int IsInMSetList(MSet *MSetList, long MsgNo)
1330 /* basicaly we are a ... */
1331 long MemberPosition;
1332 HashList *Hash = (HashList*) MSetList;
1339 if (Hash->MemberSize == 0)
1341 /** first, find out were we could fit in... */
1342 HashAt = FindInHash(Hash, MsgNo);
1344 /* we're below the first entry, so not found. */
1347 /* upper edge? move to last item */
1348 if (HashAt >= Hash->nMembersUsed)
1349 HashAt = Hash->nMembersUsed - 1;
1350 /* Match? then we got it. */
1351 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1353 /* One above possible range start? we need to move to the lower one. */
1354 else if ((HashAt > 0) &&
1355 (Hash->LookupTable[HashAt]->Key > MsgNo))
1358 /* Fetch the actual data */
1359 StartAt = Hash->LookupTable[HashAt]->Key;
1360 MemberPosition = Hash->LookupTable[HashAt]->Position;
1361 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1362 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1367 /* inside of range? */
1368 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1375 * @ingroup HashListMset
1376 * @brief frees a mset [redirects to @ref DeleteHash
1377 * @param FreeMe to be free'd
1379 void DeleteMSet(MSet **FreeMe)
1381 DeleteHash((HashList**) FreeMe);