2 * Copyright (c) 1987-2011 by the citadel.org team
4 * This program is open source software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "libcitadel.h"
28 typedef struct Payload Payload;
31 * @defgroup HashList Hashlist Key Value list implementation;
32 * Hashlist is a simple implementation of key value pairs. It doesn't implement collision handling.
33 * the Hashingalgorythm is pluggeable on creation.
34 * items are added with a functionpointer destructs them; that way complex structures can be added.
35 * if no pointer is given, simply free is used. Use @ref reference_free_handler if you don't want us to free you rmemory.
39 * @defgroup HashListData Datastructures used for the internals of HashList
44 * @defgroup HashListDebug Hashlist debugging functions
49 * @defgroup HashListPrivate Hashlist internal functions
54 * @defgroup HashListSort Hashlist sorting functions
59 * @defgroup HashListAccess Hashlist functions to access / put / delete items in(to) the list
64 * @defgroup HashListAlgorithm functions to condense Key to an integer.
69 * @defgroup HashListMset MSet is sort of a derived hashlist, its special for treating Messagesets as Citadel uses them to store access rangesx
74 * @ingroup HashListData
75 * @brief Hash Payload storage Structure; filled in linear.
78 void *Data; /**< the Data belonging to this storage */
79 DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
84 * @ingroup HashListData
85 * @brief Hash key element; sorted by key
88 long Key; /**< Numeric Hashkey comperator for hash sorting */
89 long Position; /**< Pointer to a Payload struct in the Payload Aray */
90 char *HashKey; /**< the Plaintext Hashkey */
91 long HKLen; /**< length of the Plaintext Hashkey */
92 Payload *PL; /**< pointer to our payload for sorting */
96 * @ingroup HashListData
97 * @brief Hash structure; holds arrays of Hashkey and Payload.
100 Payload **Members; /**< Our Payload members. This fills up linear */
101 HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
102 char **MyKeys; /**< this keeps the members for a call of GetHashKeys */
103 HashFunc Algorithm; /**< should we use an alternating algorithm to calc the hash values? */
104 long nMembersUsed; /**< how many pointers inside of the array are used? */
105 long nLookupTableItems; /**< how many items of the lookup table are used? */
106 long MemberSize; /**< how big is Members and LookupTable? */
107 long tainted; /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
108 long uniq; /**< are the keys going to be uniq? */
112 * @ingroup HashListData
113 * @brief Anonymous Hash Iterator Object. used for traversing the whole array from outside
116 long Position; /**< Position inside of the hash */
117 int StepWidth; /**< small? big? forward? backward? */
122 * @ingroup HashListDebug
123 * @brief Iterate over the hash and call PrintEntry.
124 * @param Hash your Hashlist structure
125 * @param Trans is called so you could for example print 'A:' if the next entries are like that.
126 * Must be aware to receive NULL in both pointers.
127 * @param PrintEntry print entry one by one
128 * @return the number of items printed
130 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
140 for (i=0; i < Hash->nLookupTableItems; i++) {
145 if (Hash->LookupTable[i - 1] == NULL)
148 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
150 if (Hash->LookupTable[i] == NULL) {
155 Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
156 KeyStr = Hash->LookupTable[i]->HashKey;
159 Trans(Previous, Next, i % 2);
160 PrintEntry(KeyStr, Next, i % 2);
167 * @ingroup HashListDebug
168 * @brief verify the contents of a hash list; here for debugging purposes.
169 * @param Hash your Hashlist structure
170 * @param First Functionpointer to allow you to print your payload
171 * @param Second Functionpointer to allow you to print your payload
174 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
179 const char *bla = "";
187 if (Hash->MyKeys != NULL)
190 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
192 printf("----------------------------------\n");
194 for (i=0; i < Hash->nLookupTableItems; i++) {
196 if (Hash->LookupTable[i] == NULL)
207 key = Hash->LookupTable[i]->Key;
208 foo = Hash->LookupTable[i]->HashKey;
214 First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
224 Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
233 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
237 printf("----------------------------------\n");
243 int TestValidateHash(HashList *TestHash)
247 if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
250 if (TestHash->nMembersUsed > TestHash->MemberSize)
253 for (i=0; i < TestHash->nMembersUsed; i++)
256 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
259 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
261 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
268 * @ingroup HashListAccess
269 * @brief instanciate a new hashlist
270 * @return the newly allocated list.
272 HashList *NewHash(int Uniq, HashFunc F)
275 NewList = malloc (sizeof(HashList));
278 memset(NewList, 0, sizeof(HashList));
280 NewList->Members = malloc(sizeof(Payload*) * 100);
281 if (NewList->Members == NULL)
286 memset(NewList->Members, 0, sizeof(Payload*) * 100);
288 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
289 if (NewList->LookupTable == NULL)
291 free(NewList->Members);
295 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
297 NewList->MemberSize = 100;
298 NewList->tainted = 0;
299 NewList->uniq = Uniq;
300 NewList->Algorithm = F;
305 int GetCount(HashList *Hash)
307 if(Hash==NULL) return 0;
308 return Hash->nLookupTableItems;
313 * @ingroup HashListPrivate
314 * @brief private destructor for one hash element.
315 * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
316 * @param Data an element to free using the user provided destructor, or just plain free
318 static void DeleteHashPayload (Payload *Data)
320 /** do we have a destructor for our payload? */
321 if (Data->Destructor)
322 Data->Destructor(Data->Data);
328 * @ingroup HashListPrivate
329 * @brief Destructor for nested hashes
331 void HDeleteHash(void *vHash)
333 HashList *FreeMe = (HashList*)vHash;
338 * @ingroup HashListAccess
339 * @brief flush the members of a hashlist
340 * Crashing? do 'print *FreeMe->LookupTable[i]'
341 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
343 void DeleteHashContent(HashList **Hash)
351 /* even if there are sparse members already deleted... */
352 for (i=0; i < FreeMe->nMembersUsed; i++)
354 /** get rid of our payload */
355 if (FreeMe->Members[i] != NULL)
357 DeleteHashPayload(FreeMe->Members[i]);
358 free(FreeMe->Members[i]);
360 /** delete our hashing data */
361 if (FreeMe->LookupTable[i] != NULL)
363 free(FreeMe->LookupTable[i]->HashKey);
364 free(FreeMe->LookupTable[i]);
367 FreeMe->nMembersUsed = 0;
369 FreeMe->nLookupTableItems = 0;
370 memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
371 memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
373 /** did s.b. want an array of our keys? free them. */
374 if (FreeMe->MyKeys != NULL)
375 free(FreeMe->MyKeys);
379 * @ingroup HashListAccess
380 * @brief destroy a hashlist and all of its members
381 * Crashing? do 'print *FreeMe->LookupTable[i]'
382 * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
384 void DeleteHash(HashList **Hash)
391 DeleteHashContent(Hash);
392 /** now, free our arrays... */
393 free(FreeMe->LookupTable);
394 free(FreeMe->Members);
396 /** buye bye cruel world. */
402 * @ingroup HashListPrivate
403 * @brief Private function to increase the hash size.
404 * @param Hash the Hasharray to increase
406 static int IncreaseHashSize(HashList *Hash)
408 /* Ok, Our space is used up. Double the available space. */
409 Payload **NewPayloadArea;
415 /** If we grew to much, this might be the place to rehash and shrink again.
416 if ((Hash->NMembersUsed > Hash->nLookupTableItems) &&
417 ((Hash->NMembersUsed - Hash->nLookupTableItems) >
418 (Hash->nLookupTableItems / 10)))
425 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
426 if (NewPayloadArea == NULL)
428 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
429 if (NewTable == NULL)
431 free(NewPayloadArea);
435 /** double our payload area */
436 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
437 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
439 Hash->Members = NewPayloadArea;
441 /** double our hashtable area */
442 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
443 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
444 free(Hash->LookupTable);
445 Hash->LookupTable = NewTable;
447 Hash->MemberSize *= 2;
453 * @ingroup HashListPrivate
454 * @brief private function to add a new item to / replace an existing in - the hashlist
455 * if the hash list is full, its re-alloced with double size.
456 * @param Hash our hashlist to manipulate
457 * @param HashPos where should we insert / replace?
458 * @param HashKeyStr the Hash-String
459 * @param HKLen length of HashKeyStr
460 * @param Data your Payload to add
461 * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
463 static int InsertHashItem(HashList *Hash,
466 const char *HashKeyStr,
469 DeleteHashDataFunc Destructor)
471 Payload *NewPayloadItem;
478 if ((Hash->nMembersUsed >= Hash->MemberSize) &&
479 (!IncreaseHashSize (Hash)))
482 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
483 if (NewPayloadItem == NULL)
485 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
486 if (NewHashKey == NULL)
488 free(NewPayloadItem);
491 HashKeyOrgVal = (char *) malloc (HKLen + 1);
492 if (HashKeyOrgVal == NULL)
495 free(NewPayloadItem);
500 /** Arrange the payload */
501 NewPayloadItem->Data = Data;
502 NewPayloadItem->Destructor = Destructor;
503 /** Arrange the hashkey */
504 NewHashKey->HKLen = HKLen;
505 NewHashKey->HashKey = HashKeyOrgVal;
506 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
507 NewHashKey->Key = HashBinKey;
508 NewHashKey->PL = NewPayloadItem;
509 /** our payload is queued at the end... */
510 NewHashKey->Position = Hash->nMembersUsed;
511 /** but if we should be sorted into a specific place... */
512 if ((Hash->nLookupTableItems != 0) &&
513 (HashPos != Hash->nLookupTableItems) ) {
516 ItemsAfter = Hash->nLookupTableItems - HashPos;
517 /** make space were we can fill us in */
520 memmove(&Hash->LookupTable[HashPos + 1],
521 &Hash->LookupTable[HashPos],
522 ItemsAfter * sizeof(HashKey*));
526 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
527 Hash->LookupTable[HashPos] = NewHashKey;
528 Hash->nMembersUsed++;
529 Hash->nLookupTableItems++;
534 * @ingroup HashListSort
535 * @brief if the user has tainted the hash, but wants to insert / search items by their key
536 * we need to search linear through the array. You have been warned that this will take more time!
537 * @param Hash Our Hash to manipulate
538 * @param HashBinKey the Hash-Number to lookup.
539 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
541 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
548 for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
549 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
557 * @ingroup HashListPrivate
558 * @brief Private function to lookup the Item / the closest position to put it in
559 * @param Hash Our Hash to manipulate
560 * @param HashBinKey the Hash-Number to lookup.
561 * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
563 static long FindInHash(HashList *Hash, long HashBinKey)
572 return FindInTaintedHash(Hash, HashBinKey);
574 SearchPos = Hash->nLookupTableItems / 2;
575 StepWidth = SearchPos / 2;
576 while ((SearchPos > 0) &&
577 (SearchPos < Hash->nLookupTableItems))
579 /** Did we find it? */
580 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
583 /** are we Aproximating in big steps? */
585 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
586 SearchPos -= StepWidth;
588 SearchPos += StepWidth;
591 else { /** We are right next to our target, within 4 positions */
592 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
593 if ((SearchPos > 0) &&
594 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
599 if ((SearchPos + 1 < Hash->nLookupTableItems) &&
600 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
612 * @ingroup HashListAlgorithm
613 * @brief another hashing algorithm; treat it as just a pointer to int.
614 * @param str Our pointer to the int value
615 * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
616 * @return the calculated hash value
618 long Flathash(const char *str, long len)
620 if (len != sizeof (int))
622 else return *(int*)str;
626 * @ingroup HashListAlgorithm
627 * @brief another hashing algorithm; treat it as just a pointer to long.
628 * @param str Our pointer to the long value
629 * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
630 * @return the calculated hash value
632 long lFlathash(const char *str, long len)
634 if (len != sizeof (long))
636 else return *(long*)str;
640 * @ingroup HashListPrivate
641 * @brief private abstract wrapper around the hashing algorithm
642 * @param HKey the hash string
643 * @param HKLen length of HKey
644 * @return the calculated hash value
646 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
651 if (Hash->Algorithm == NULL)
652 return hashlittle(HKey, HKLen, 9283457);
654 return Hash->Algorithm(HKey, HKLen);
659 * @ingroup HashListAccess
660 * @brief Add a new / Replace an existing item in the Hash
661 * @param Hash the list to manipulate
662 * @param HKey the hash-string to store Data under
663 * @param HKLen Length of HKey
664 * @param Data the payload you want to associate with HKey
665 * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
667 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
675 /** first, find out were we could fit in... */
676 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
677 HashAt = FindInHash(Hash, HashBinKey);
679 if ((HashAt >= Hash->MemberSize) &&
680 (!IncreaseHashSize (Hash)))
683 /** oh, we're brand new... */
684 if (Hash->LookupTable[HashAt] == NULL) {
685 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
686 }/** Insert Before? */
687 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
688 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
689 }/** Insert After? */
690 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
691 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
693 else { /** Ok, we have a colision. replace it. */
697 PayloadPos = Hash->LookupTable[HashAt]->Position;
698 DeleteHashPayload(Hash->Members[PayloadPos]);
699 Hash->Members[PayloadPos]->Data = Data;
700 Hash->Members[PayloadPos]->Destructor = DeleteIt;
703 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
709 * @ingroup HashListAccess
710 * @brief Lookup the Data associated with HKey
711 * @param Hash the Hashlist to search in
712 * @param HKey the hashkey to look up
713 * @param HKLen length of HKey
714 * @param Data returns the Data associated with HKey
715 * @return 0 if not found, 1 if.
717 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
729 /** first, find out were we could be... */
730 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
731 HashAt = FindInHash(Hash, HashBinKey);
732 if ((HashAt < 0) || /**< Not found at the lower edge? */
733 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
734 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
738 else { /** GOTCHA! */
741 MemberPosition = Hash->LookupTable[HashAt]->Position;
742 *Data = Hash->Members[MemberPosition]->Data;
748 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
754 * @ingroup HashListAccess
755 * @brief get the Keys present in this hash, similar to array_keys() in PHP
756 * Attention: List remains to Hash! don't modify or free it!
757 * @param Hash Your Hashlist to extract the keys from
758 * @param List returns the list of hashkeys stored in Hash
760 int GetHashKeys(HashList *Hash, char ***List)
767 if (Hash->MyKeys != NULL)
770 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
771 if (Hash->MyKeys == NULL)
774 for (i=0; i < Hash->nLookupTableItems; i++)
776 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
778 *List = (char**)Hash->MyKeys;
779 return Hash->nLookupTableItems;
783 * @ingroup HashListAccess
784 * @brief creates a hash-linear iterator object
785 * @param Hash the list we reference
786 * @param StepWidth in which step width should we iterate?
787 * If negative, the last position matching the
788 * step-raster is provided.
789 * @return the hash iterator
791 HashPos *GetNewHashPos(HashList *Hash, int StepWidth)
795 Ret = (HashPos*)malloc(sizeof(HashPos));
800 Ret->StepWidth = StepWidth;
803 if (Ret->StepWidth < 0) {
804 Ret->Position = Hash->nLookupTableItems - 1;
813 * @ingroup HashListAccess
814 * @brief Set iterator object to point to key. If not found, don't change iterator
815 * @param Hash the list we reference
816 * @param HKey key to search for
817 * @param HKLen length of key
818 * @param At HashPos to update
819 * @return 0 if not found
821 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
832 /** first, find out were we could be... */
833 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
834 HashAt = FindInHash(Hash, HashBinKey);
835 if ((HashAt < 0) || /**< Not found at the lower edge? */
836 (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
837 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
841 At->Position = HashAt;
846 * @ingroup HashListAccess
847 * @brief Delete from the Hash the entry at Position
848 * @param Hash the list we reference
849 * @param At the position within the Hash
850 * @return 0 if not found
852 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
858 /* if lockable, lock here */
859 if ((Hash == NULL) ||
860 (At->Position >= Hash->nLookupTableItems) ||
861 (At->Position < 0) ||
862 (At->Position > Hash->nLookupTableItems))
868 FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
869 Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
872 /** delete our hashing data */
873 if (Hash->LookupTable[At->Position] != NULL)
875 free(Hash->LookupTable[At->Position]->HashKey);
876 free(Hash->LookupTable[At->Position]);
877 if (At->Position < Hash->nLookupTableItems)
879 memmove(&Hash->LookupTable[At->Position],
880 &Hash->LookupTable[At->Position + 1],
881 (Hash->nLookupTableItems - At->Position - 1) *
884 Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
887 Hash->LookupTable[At->Position] = NULL;
888 Hash->nLookupTableItems--;
893 /** get rid of our payload */
896 DeleteHashPayload(FreeMe);
903 * @ingroup HashListAccess
904 * @brief retrieve the counter from the itteratoor
906 * @param At the Iterator to analyze
907 * @return the n'th hashposition we point at
909 int GetHashPosCounter(HashList *Hash, HashPos *At)
911 if ((Hash == NULL) ||
912 (At->Position >= Hash->nLookupTableItems) ||
913 (At->Position < 0) ||
914 (At->Position > Hash->nLookupTableItems))
920 * @ingroup HashListAccess
921 * @brief frees a linear hash iterator
923 void DeleteHashPos(HashPos **DelMe)
934 * @ingroup HashListAccess
935 * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
936 * @param Hash your Hashlist to follow
937 * @param At the position to retrieve the Item from and move forward afterwards
938 * @param HKLen returns Length of Hashkey Returned
939 * @param HashKey returns the Hashkey corrosponding to HashPos
940 * @param Data returns the Data found at HashPos
941 * @return whether the item was found or not.
943 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
947 if ((Hash == NULL) ||
948 (At->Position >= Hash->nLookupTableItems) ||
949 (At->Position < 0) ||
950 (At->Position > Hash->nLookupTableItems))
952 *HKLen = Hash->LookupTable[At->Position]->HKLen;
953 *HashKey = Hash->LookupTable[At->Position]->HashKey;
954 PayloadPos = Hash->LookupTable[At->Position]->Position;
955 *Data = Hash->Members[PayloadPos]->Data;
957 /* Position is NULL-Based, while Stepwidth is not... */
958 if ((At->Position % abs(At->StepWidth)) == 0)
959 At->Position += At->StepWidth;
961 At->Position += ((At->Position) % abs(At->StepWidth)) *
962 (At->StepWidth / abs(At->StepWidth));
967 * @ingroup HashListAccess
968 * @brief Get the data located where HashPos Iterator points at
969 * @param Hash your Hashlist to follow
970 * @param At the position retrieve the data from
971 * @param HKLen returns Length of Hashkey Returned
972 * @param HashKey returns the Hashkey corrosponding to HashPos
973 * @param Data returns the Data found at HashPos
974 * @return whether the item was found or not.
976 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
980 if ((Hash == NULL) ||
981 (At->Position >= Hash->nLookupTableItems) ||
982 (At->Position < 0) ||
983 (At->Position > Hash->nLookupTableItems))
985 *HKLen = Hash->LookupTable[At->Position]->HKLen;
986 *HashKey = Hash->LookupTable[At->Position]->HashKey;
987 PayloadPos = Hash->LookupTable[At->Position]->Position;
988 *Data = Hash->Members[PayloadPos]->Data;
994 * @ingroup HashListAccess
995 * @brief Move HashPos one forward
996 * @param Hash your Hashlist to follow
997 * @param At the position to move forward
998 * @return whether there is a next item or not.
1000 int NextHashPos(HashList *Hash, HashPos *At)
1002 if ((Hash == NULL) ||
1003 (At->Position >= Hash->nLookupTableItems) ||
1004 (At->Position < 0) ||
1005 (At->Position > Hash->nLookupTableItems))
1008 /* Position is NULL-Based, while Stepwidth is not... */
1009 if ((At->Position % abs(At->StepWidth)) == 0)
1010 At->Position += At->StepWidth;
1012 At->Position += ((At->Position) % abs(At->StepWidth)) *
1013 (At->StepWidth / abs(At->StepWidth));
1014 return !((At->Position >= Hash->nLookupTableItems) ||
1015 (At->Position < 0) ||
1016 (At->Position > Hash->nLookupTableItems));
1020 * @ingroup HashListAccess
1021 * @brief Get the data located where At points to
1022 * note: you should prefer iterator operations instead of using me.
1023 * @param Hash your Hashlist peek from
1024 * @param At get the item in the position At.
1025 * @param HKLen returns Length of Hashkey Returned
1026 * @param HashKey returns the Hashkey corrosponding to HashPos
1027 * @param Data returns the Data found at HashPos
1028 * @return whether the item was found or not.
1030 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1034 if ((Hash == NULL) ||
1036 (At >= Hash->nLookupTableItems))
1038 *HKLen = Hash->LookupTable[At]->HKLen;
1039 *HashKey = Hash->LookupTable[At]->HashKey;
1040 PayloadPos = Hash->LookupTable[At]->Position;
1041 *Data = Hash->Members[PayloadPos]->Data;
1046 * @ingroup HashListSort
1047 * @brief Get the data located where At points to
1048 * note: you should prefer iterator operations instead of using me.
1049 * @param Hash your Hashlist peek from
1050 * @param HKLen returns Length of Hashkey Returned
1051 * @param HashKey returns the Hashkey corrosponding to HashPos
1052 * @param Data returns the Data found at HashPos
1053 * @return whether the item was found or not.
1056 long GetHashIDAt(HashList *Hash,long At)
1058 if ((Hash == NULL) ||
1060 (At > Hash->nLookupTableItems))
1063 return Hash->LookupTable[At]->Key;
1069 * @ingroup HashListSort
1070 * @brief sorting function for sorting the Hash alphabeticaly by their strings
1071 * @param Key1 first item
1072 * @param Key2 second item
1074 static int SortByKeys(const void *Key1, const void* Key2)
1076 HashKey *HKey1, *HKey2;
1077 HKey1 = *(HashKey**) Key1;
1078 HKey2 = *(HashKey**) Key2;
1080 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1084 * @ingroup HashListSort
1085 * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1086 * @param Key1 first item
1087 * @param Key2 second item
1089 static int SortByKeysRev(const void *Key1, const void* Key2)
1091 HashKey *HKey1, *HKey2;
1092 HKey1 = *(HashKey**) Key1;
1093 HKey2 = *(HashKey**) Key2;
1095 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1099 * @ingroup HashListSort
1100 * @brief sorting function to regain hash-sequence and revert tainted status
1101 * @param Key1 first item
1102 * @param Key2 second item
1104 static int SortByHashKeys(const void *Key1, const void* Key2)
1106 HashKey *HKey1, *HKey2;
1107 HKey1 = *(HashKey**) Key1;
1108 HKey2 = *(HashKey**) Key2;
1110 return HKey1->Key > HKey2->Key;
1115 * @ingroup HashListSort
1116 * @brief sort the hash alphabeticaly by their keys.
1117 * Caution: This taints the hashlist, so accessing it later
1118 * will be significantly slower! You can un-taint it by SortByHashKeyStr
1119 * @param Hash the list to sort
1120 * @param Order 0/1 Forward/Backward
1122 void SortByHashKey(HashList *Hash, int Order)
1124 if (Hash->nLookupTableItems < 2)
1126 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*),
1127 (Order)?SortByKeys:SortByKeysRev);
1132 * @ingroup HashListSort
1133 * @brief sort the hash by their keys (so it regains untainted state).
1134 * this will result in the sequence the hashing allgorithm produces it by default.
1135 * @param Hash the list to sort
1137 void SortByHashKeyStr(HashList *Hash)
1140 if (Hash->nLookupTableItems < 2)
1142 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1147 * @ingroup HashListSort
1148 * @brief gives user sort routines access to the hash payload
1149 * @param HashVoid to retrieve Data to
1150 * @return Data belonging to HashVoid
1152 const void *GetSearchPayload(const void *HashVoid)
1154 return (*(HashKey**)HashVoid)->PL->Data;
1158 * @ingroup HashListSort
1159 * @brief sort the hash by your sort function. see the following sample.
1160 * this will result in the sequence the hashing allgorithm produces it by default.
1161 * @param Hash the list to sort
1162 * @param SortBy Sortfunction; see below how to implement this
1164 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1166 if (Hash->nLookupTableItems < 2)
1168 qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1176 * given you've put char * into your hash as a payload, a sort function might
1178 * int SortByChar(const void* First, const void* Second)
1181 * a = (char*) GetSearchPayload(First);
1182 * b = (char*) GetSearchPayload(Second);
1183 * return strcmp (a, b);
1189 * @ingroup HashListAccess
1190 * @brief Generic function to free a reference.
1191 * since a reference actualy isn't needed to be freed, do nothing.
1193 void reference_free_handler(void *ptr)
1200 * @ingroup HashListAlgorithm
1201 * This exposes the hashlittle() function to consumers.
1203 int HashLittle(const void *key, size_t length) {
1204 return (int)hashlittle(key, length, 1);
1209 * @ingroup HashListMset
1210 * @brief parses an MSet string into a list for later use
1211 * @param MSetList List to be read from MSetStr
1212 * @param MSetStr String containing the list
1214 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1216 const char *POS = NULL, *SetPOS = NULL;
1219 long StartSet, EndSet;
1223 if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1226 OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1230 ThisMSet = NewHash(0, lFlathash);
1231 if (ThisMSet == NULL)
1233 FreeStrBuf(&OneSet);
1237 *MSetList = (MSet*) ThisMSet;
1239 /* an MSet is a coma separated value list. */
1240 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1244 /* One set may consist of two Numbers: Start + optional End */
1245 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1246 EndSet = 0; /* no range is our default. */
1247 /* do we have an end (aka range?) */
1248 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1250 if (*(SetPOS) == '*')
1251 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1253 /* in other cases, get the EndPoint */
1254 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1257 pEndSet = (long*) malloc (sizeof(long));
1258 if (pEndSet == NULL)
1260 FreeStrBuf(&OneSet);
1261 DeleteHash(&ThisMSet);
1266 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1267 /* if we don't have another, we're done. */
1268 if (POS == StrBufNOTNULL)
1270 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1272 FreeStrBuf(&OneSet);
1278 * @ingroup HashListMset
1279 * @brief checks whether a message is inside a mset
1280 * @param MSetList List to search for MsgNo
1281 * @param MsgNo number to search in mset
1283 int IsInMSetList(MSet *MSetList, long MsgNo)
1285 /* basicaly we are a ... */
1286 long MemberPosition;
1287 HashList *Hash = (HashList*) MSetList;
1294 if (Hash->MemberSize == 0)
1296 /** first, find out were we could fit in... */
1297 HashAt = FindInHash(Hash, MsgNo);
1299 /* we're below the first entry, so not found. */
1302 /* upper edge? move to last item */
1303 if (HashAt >= Hash->nMembersUsed)
1304 HashAt = Hash->nMembersUsed - 1;
1305 /* Match? then we got it. */
1306 else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1308 /* One above possible range start? we need to move to the lower one. */
1309 else if ((HashAt > 0) &&
1310 (Hash->LookupTable[HashAt]->Key > MsgNo))
1313 /* Fetch the actual data */
1314 StartAt = Hash->LookupTable[HashAt]->Key;
1315 MemberPosition = Hash->LookupTable[HashAt]->Position;
1316 EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1317 if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1322 /* inside of range? */
1323 if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1330 * @ingroup HashListMset
1331 * @brief frees a mset [redirects to @ref DeleteHash
1332 * @param FreeMe to be free'd
1334 void DeleteMSet(MSet **FreeMe)
1336 DeleteHash((HashList**) FreeMe);