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 HashListAlgorithm
662 * @brief another hashing algorithm; accepts exactly 4 characters, convert it to a hash key.
663 * @param str Our pointer to the long value
664 * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
665 * @return the calculated hash value
667 long FourHash(const char *key, long length)
671 const unsigned char *ptr = (const unsigned char*)key;
673 for (i = 0; i < 4; i++, ptr ++)
684 * @ingroup HashListPrivate
685 * @brief private abstract wrapper around the hashing algorithm
686 * @param HKey the hash string
687 * @param HKLen length of HKey
688 * @return the calculated hash value
690 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
695 if (Hash->Algorithm == NULL)
696 return hashlittle(HKey, HKLen, 9283457);
698 return Hash->Algorithm(HKey, HKLen);
703 * @ingroup HashListAccess
704 * @brief Add a new / Replace an existing item in the Hash
705 * @param Hash the list to manipulate
706 * @param HKey the hash-string to store Data under
707 * @param HKLen Length of HKey
708 * @param Data the payload you want to associate with HKey
709 * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
711 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
719 /** first, find out were we could fit in... */
720 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
721 HashAt = FindInHash(Hash, HashBinKey);
723 if ((HashAt >= Hash->MemberSize) &&
724 (!IncreaseHashSize (Hash)))
727 /** oh, we're brand new... */
728 if (Hash->LookupTable[HashAt] == NULL) {
729 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
730 }/** Insert Before? */
731 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
732 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
733 }/** Insert After? */
734 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
735 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
737 else { /** Ok, we have a colision. replace it. */
741 PayloadPos = Hash->LookupTable[HashAt]->Position;
742 DeleteHashPayload(Hash->Members[PayloadPos]);
743 Hash->Members[PayloadPos]->Data = Data;
744 Hash->Members[PayloadPos]->Destructor = DeleteIt;
747 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
753 * @ingroup HashListAccess
754 * @brief Lookup the Data associated with HKey
755 * @param Hash the Hashlist to search in
756 * @param HKey the hashkey to look up
757 * @param HKLen length of HKey
758 * @param Data returns the Data associated with HKey
759 * @return 0 if not found, 1 if.
761 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
773 /** first, find out were we could be... */
774 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
775 HashAt = FindInHash(Hash, HashBinKey);
776 if ((HashAt < 0) || /**< Not found at the lower edge? */
777 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
778 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
782 else { /** GOTCHA! */
785 MemberPosition = Hash->LookupTable[HashAt]->Position;
786 *Data = Hash->Members[MemberPosition]->Data;
792 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
798 * @ingroup HashListAccess
799 * @brief get the Keys present in this hash, similar to array_keys() in PHP
800 * Attention: List remains to Hash! don't modify or free it!
801 * @param Hash Your Hashlist to extract the keys from
802 * @param List returns the list of hashkeys stored in Hash
804 int GetHashKeys(HashList *Hash, char ***List)
811 if (Hash->MyKeys != NULL)
814 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
815 if (Hash->MyKeys == NULL)
818 for (i=0; i < Hash->nLookupTableItems; i++)
820 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
822 *List = (char**)Hash->MyKeys;
823 return Hash->nLookupTableItems;
827 * @ingroup HashListAccess
828 * @brief creates a hash-linear iterator object
829 * @param Hash the list we reference
830 * @param StepWidth in which step width should we iterate?
831 * If negative, the last position matching the
832 * step-raster is provided.
833 * @return the hash iterator
835 HashPos *GetNewHashPos(const HashList *Hash, int StepWidth)
839 Ret = (HashPos*)malloc(sizeof(HashPos));
844 Ret->StepWidth = StepWidth;
847 if (Ret->StepWidth < 0) {
848 Ret->Position = Hash->nLookupTableItems - 1;
857 * @ingroup HashListAccess
858 * @brief resets a hash-linear iterator object
859 * @param Hash the list we reference
860 * @param StepWidth in which step width should we iterate?
861 * @param it the iterator object to manipulate
862 * If negative, the last position matching the
863 * step-raster is provided.
864 * @return the hash iterator
866 void RewindHashPos(const HashList *Hash, HashPos *it, int StepWidth)
869 it->StepWidth = StepWidth;
872 if (it->StepWidth < 0) {
873 it->Position = Hash->nLookupTableItems - 1;
881 * @ingroup HashListAccess
882 * @brief Set iterator object to point to key. If not found, don't change iterator
883 * @param Hash the list we reference
884 * @param HKey key to search for
885 * @param HKLen length of key
886 * @param At HashPos to update
887 * @return 0 if not found
889 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
900 /** first, find out were we could be... */
901 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
902 HashAt = FindInHash(Hash, HashBinKey);
903 if ((HashAt < 0) || /**< Not found at the lower edge? */
904 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
905 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
909 At->Position = HashAt;
914 * @ingroup HashListAccess
915 * @brief Delete from the Hash the entry at Position
916 * @param Hash the list we reference
917 * @param At the position within the Hash
918 * @return 0 if not found
920 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
926 /* if lockable, lock here */
927 if ((Hash == NULL) ||
928 (At->Position >= Hash->nLookupTableItems) ||
929 (At->Position < 0) ||
930 (At->Position > Hash->nLookupTableItems))
936 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
937 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
940 /** delete our hashing data */
941 if (Hash->LookupTable[At->Position] != NULL)
943 free(Hash->LookupTable[At->Position]->HashKey);
944 free(Hash->LookupTable[At->Position]);
945 if (At->Position < Hash->nLookupTableItems)
947 memmove(&Hash->LookupTable[At->Position],
948 &Hash->LookupTable[At->Position + 1],
949 (Hash->nLookupTableItems - At->Position - 1) *
952 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
955 Hash->LookupTable[At->Position] = NULL;
956 Hash->nLookupTableItems--;
961 /** get rid of our payload */
964 DeleteHashPayload(FreeMe);
971 * @ingroup HashListAccess
972 * @brief retrieve the counter from the itteratoor
974 * @param At the Iterator to analyze
975 * @return the n'th hashposition we point at
977 int GetHashPosCounter(HashList *Hash, HashPos *At)
979 if ((Hash == NULL) ||
980 (At->Position >= Hash->nLookupTableItems) ||
981 (At->Position < 0) ||
982 (At->Position > Hash->nLookupTableItems))
988 * @ingroup HashListAccess
989 * @brief frees a linear hash iterator
991 void DeleteHashPos(HashPos **DelMe)
1002 * @ingroup HashListAccess
1003 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
1004 * @param Hash your Hashlist to follow
1005 * @param At the position to retrieve the Item from and move forward afterwards
1006 * @param HKLen returns Length of Hashkey Returned
1007 * @param HashKey returns the Hashkey corrosponding to HashPos
1008 * @param Data returns the Data found at HashPos
1009 * @return whether the item was found or not.
1011 int GetNextHashPos(const HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1015 if ((Hash == NULL) ||
1016 (At->Position >= Hash->nLookupTableItems) ||
1017 (At->Position < 0) ||
1018 (At->Position > Hash->nLookupTableItems))
1020 *HKLen = Hash->LookupTable[At->Position]->HKLen;
1021 *HashKey = Hash->LookupTable[At->Position]->HashKey;
1022 PayloadPos = Hash->LookupTable[At->Position]->Position;
1023 *Data = Hash->Members[PayloadPos]->Data;
1025 /* Position is NULL-Based, while Stepwidth is not... */
1026 if ((At->Position % abs(At->StepWidth)) == 0)
1027 At->Position += At->StepWidth;
1029 At->Position += ((At->Position) % abs(At->StepWidth)) *
1030 (At->StepWidth / abs(At->StepWidth));
1035 * @ingroup HashListAccess
1036 * @brief Get the data located where HashPos Iterator points at
1037 * @param Hash your Hashlist to follow
1038 * @param At the position retrieve the data from
1039 * @param HKLen returns Length of Hashkey Returned
1040 * @param HashKey returns the Hashkey corrosponding to HashPos
1041 * @param Data returns the Data found at HashPos
1042 * @return whether the item was found or not.
1044 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1048 if ((Hash == NULL) ||
1049 (At->Position >= Hash->nLookupTableItems) ||
1050 (At->Position < 0) ||
1051 (At->Position > Hash->nLookupTableItems))
1053 *HKLen = Hash->LookupTable[At->Position]->HKLen;
1054 *HashKey = Hash->LookupTable[At->Position]->HashKey;
1055 PayloadPos = Hash->LookupTable[At->Position]->Position;
1056 *Data = Hash->Members[PayloadPos]->Data;
1062 * @ingroup HashListAccess
1063 * @brief Move HashPos one forward
1064 * @param Hash your Hashlist to follow
1065 * @param At the position to move forward
1066 * @return whether there is a next item or not.
1068 int NextHashPos(HashList *Hash, HashPos *At)
1070 if ((Hash == NULL) ||
1071 (At->Position >= Hash->nLookupTableItems) ||
1072 (At->Position < 0) ||
1073 (At->Position > Hash->nLookupTableItems))
1076 /* Position is NULL-Based, while Stepwidth is not... */
1077 if ((At->Position % abs(At->StepWidth)) == 0)
1078 At->Position += At->StepWidth;
1080 At->Position += ((At->Position) % abs(At->StepWidth)) *
1081 (At->StepWidth / abs(At->StepWidth));
1082 return !((At->Position >= Hash->nLookupTableItems) ||
1083 (At->Position < 0) ||
1084 (At->Position > Hash->nLookupTableItems));
1088 * @ingroup HashListAccess
1089 * @brief Get the data located where At points to
1090 * note: you should prefer iterator operations instead of using me.
1091 * @param Hash your Hashlist peek from
1092 * @param At get the item in the position At.
1093 * @param HKLen returns Length of Hashkey Returned
1094 * @param HashKey returns the Hashkey corrosponding to HashPos
1095 * @param Data returns the Data found at HashPos
1096 * @return whether the item was found or not.
1098 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1102 if ((Hash == NULL) ||
1104 (At >= Hash->nLookupTableItems))
1106 *HKLen = Hash->LookupTable[At]->HKLen;
1107 *HashKey = Hash->LookupTable[At]->HashKey;
1108 PayloadPos = Hash->LookupTable[At]->Position;
1109 *Data = Hash->Members[PayloadPos]->Data;
1114 * @ingroup HashListSort
1115 * @brief Get the data located where At points to
1116 * note: you should prefer iterator operations instead of using me.
1117 * @param Hash your Hashlist peek from
1118 * @param HKLen returns Length of Hashkey Returned
1119 * @param HashKey returns the Hashkey corrosponding to HashPos
1120 * @param Data returns the Data found at HashPos
1121 * @return whether the item was found or not.
1124 long GetHashIDAt(HashList *Hash,long At)
1126 if ((Hash == NULL) ||
1128 (At > Hash->nLookupTableItems))
1131 return Hash->LookupTable[At]->Key;
1137 * @ingroup HashListSort
1138 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1139 * @param Key1 first item
1140 * @param Key2 second item
1142 static int SortByKeys(const void *Key1, const void* Key2)
1144 HashKey *HKey1, *HKey2;
1145 HKey1 = *(HashKey**) Key1;
1146 HKey2 = *(HashKey**) Key2;
1148 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1152 * @ingroup HashListSort
1153 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1154 * @param Key1 first item
1155 * @param Key2 second item
1157 static int SortByKeysRev(const void *Key1, const void* Key2)
1159 HashKey *HKey1, *HKey2;
1160 HKey1 = *(HashKey**) Key1;
1161 HKey2 = *(HashKey**) Key2;
1163 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1167 * @ingroup HashListSort
1168 * @brief sorting function to regain hash-sequence and revert tainted status
1169 * @param Key1 first item
1170 * @param Key2 second item
1172 static int SortByHashKeys(const void *Key1, const void* Key2)
1174 HashKey *HKey1, *HKey2;
1175 HKey1 = *(HashKey**) Key1;
1176 HKey2 = *(HashKey**) Key2;
1178 return HKey1->Key > HKey2->Key;
1183 * @ingroup HashListSort
1184 * @brief sort the hash alphabeticaly by their keys.
1185 * Caution: This taints the hashlist, so accessing it later
1186 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1187 * @param Hash the list to sort
1188 * @param Order 0/1 Forward/Backward
1190 void SortByHashKey(HashList *Hash, int Order)
1192 if (Hash->nLookupTableItems < 2)
1194 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1195 (Order)?SortByKeys:SortByKeysRev);
1200 * @ingroup HashListSort
1201 * @brief sort the hash by their keys (so it regains untainted state).
1202 * this will result in the sequence the hashing allgorithm produces it by default.
1203 * @param Hash the list to sort
1205 void SortByHashKeyStr(HashList *Hash)
1208 if (Hash->nLookupTableItems < 2)
1210 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1215 * @ingroup HashListSort
1216 * @brief gives user sort routines access to the hash payload
1217 * @param HashVoid to retrieve Data to
1218 * @return Data belonging to HashVoid
1220 const void *GetSearchPayload(const void *HashVoid)
1222 return (*(HashKey**)HashVoid)->PL->Data;
1226 * @ingroup HashListSort
1227 * @brief sort the hash by your sort function. see the following sample.
1228 * this will result in the sequence the hashing allgorithm produces it by default.
1229 * @param Hash the list to sort
1230 * @param SortBy Sortfunction; see below how to implement this
1232 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1234 if (Hash->nLookupTableItems < 2)
1236 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1244 * given you've put char * into your hash as a payload, a sort function might
1246 * int SortByChar(const void* First, const void* Second)
1249 * a = (char*) GetSearchPayload(First);
1250 * b = (char*) GetSearchPayload(Second);
1251 * return strcmp (a, b);
1257 * @ingroup HashListAccess
1258 * @brief Generic function to free a reference.
1259 * since a reference actualy isn't needed to be freed, do nothing.
1261 void reference_free_handler(void *ptr)
1268 * @ingroup HashListAlgorithm
1269 * This exposes the hashlittle() function to consumers.
1271 int HashLittle(const void *key, size_t length) {
1272 return (int)hashlittle(key, length, 1);
1277 * @ingroup HashListMset
1278 * @brief parses an MSet string into a list for later use
1279 * @param MSetList List to be read from MSetStr
1280 * @param MSetStr String containing the list
1282 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1284 const char *POS = NULL, *SetPOS = NULL;
1287 long StartSet, EndSet;
1291 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1294 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1298 ThisMSet = NewHash(0, lFlathash);
1299 if (ThisMSet == NULL)
1301 FreeStrBuf(&OneSet);
1305 *MSetList = (MSet*) ThisMSet;
1307 /* an MSet is a coma separated value list. */
1308 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1312 /* One set may consist of two Numbers: Start + optional End */
1313 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1314 EndSet = 0; /* no range is our default. */
1315 /* do we have an end (aka range?) */
1316 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1318 if (*(SetPOS) == '*')
1319 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1321 /* in other cases, get the EndPoint */
1322 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1325 pEndSet = (long*) malloc (sizeof(long));
1326 if (pEndSet == NULL)
1328 FreeStrBuf(&OneSet);
1329 DeleteHash(&ThisMSet);
1334 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1335 /* if we don't have another, we're done. */
1336 if (POS == StrBufNOTNULL)
1338 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1340 FreeStrBuf(&OneSet);
1346 * @ingroup HashListMset
1347 * @brief checks whether a message is inside a mset
1348 * @param MSetList List to search for MsgNo
1349 * @param MsgNo number to search in mset
1351 int IsInMSetList(MSet *MSetList, long MsgNo)
1353 /* basicaly we are a ... */
1354 long MemberPosition;
1355 HashList *Hash = (HashList*) MSetList;
1362 if (Hash->MemberSize == 0)
1364 /** first, find out were we could fit in... */
1365 HashAt = FindInHash(Hash, MsgNo);
1367 /* we're below the first entry, so not found. */
1370 /* upper edge? move to last item */
1371 if (HashAt >= Hash->nMembersUsed)
1372 HashAt = Hash->nMembersUsed - 1;
1373 /* Match? then we got it. */
1374 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1376 /* One above possible range start? we need to move to the lower one. */
1377 else if ((HashAt > 0) &&
1378 (Hash->LookupTable[HashAt]->Key > MsgNo))
1381 /* Fetch the actual data */
1382 StartAt = Hash->LookupTable[HashAt]->Key;
1383 MemberPosition = Hash->LookupTable[HashAt]->Position;
1384 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1385 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1390 /* inside of range? */
1391 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1398 * @ingroup HashListMset
1399 * @brief frees a mset [redirects to @ref DeleteHash
1400 * @param FreeMe to be free'd
1402 void DeleteMSet(MSet **FreeMe)
1404 DeleteHash((HashList**) FreeMe);