]> code.citadel.org Git - citadel.git/blobdiff - libcitadel/lib/hash.c
* need to revalidate start in any case to be exact.
[citadel.git] / libcitadel / lib / hash.c
index 0c039ed8e2dad0699839f901a394b26c14ab8b7f..29f145894218e6b8b5d85713db4ea7bdbba6df27 100644 (file)
@@ -1,6 +1,7 @@
 #include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
 //dbg
 #include <stdio.h>
 #include "libcitadel.h"
@@ -37,6 +38,7 @@ struct HashList {
        char **MyKeys;         /**< this keeps the members for a call of GetHashKeys */
        HashFunc Algorithm;    /**< should we use an alternating algorithm to calc the hash values? */
        long nMembersUsed;     /**< how many pointers inside of the array are used? */
+       long nLookupTableItems; /**< how many items of the lookup table are used? */
        long MemberSize;       /**< how big is Members and LookupTable? */
        long tainted;          /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
        long uniq;             /**< are the keys going to be uniq? */
@@ -69,7 +71,7 @@ int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry
        if (Hash == NULL)
                return 0;
 
-       for (i=0; i < Hash->nMembersUsed; i++) {
+       for (i=0; i < Hash->nLookupTableItems; i++) {
                if (i==0) {
                        Previous = NULL;
                }
@@ -116,11 +118,11 @@ int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Secon
        if (Hash->MyKeys != NULL)
                free (Hash->MyKeys);
 
-       Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
+       Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
 #ifdef DEBUG
        printf("----------------------------------\n");
 #endif
-       for (i=0; i < Hash->nMembersUsed; i++) {
+       for (i=0; i < Hash->nLookupTableItems; i++) {
                
                if (Hash->LookupTable[i] == NULL)
                {
@@ -179,7 +181,7 @@ HashList *NewHash(int Uniq, HashFunc F)
 int GetCount(HashList *Hash)
 {
        if(Hash==NULL) return 0;
-       return Hash->nMembersUsed;
+       return Hash->nLookupTableItems;
 }
 
 
@@ -219,6 +221,7 @@ void DeleteHash(HashList **Hash)
        FreeMe = *Hash;
        if (FreeMe == NULL)
                return;
+       /* even if there are sparse members already deleted... */
        for (i=0; i < FreeMe->nMembersUsed; i++)
        {
                /** get rid of our payload */
@@ -258,6 +261,16 @@ static void IncreaseHashSize(HashList *Hash)
        if (Hash == NULL)
                return ;
 
+       /** If we grew to much, this might be the place to rehash and shrink again.
+       if ((Hash->NMembersUsed > Hash->nLookupTableItems) && 
+           ((Hash->NMembersUsed - Hash->nLookupTableItems) > 
+            (Hash->nLookupTableItems / 10)))
+       {
+
+
+       }
+       */
+
        /** double our payload area */
        NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
        memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
@@ -317,11 +330,11 @@ static void InsertHashItem(HashList *Hash,
        /** our payload is queued at the end... */
        NewHashKey->Position = Hash->nMembersUsed;
        /** but if we should be sorted into a specific place... */
-       if ((Hash->nMembersUsed != 0) && 
-           (HashPos != Hash->nMembersUsed) ) {
+       if ((Hash->nLookupTableItems != 0) && 
+           (HashPos != Hash->nLookupTableItems) ) {
                long ItemsAfter;
 
-               ItemsAfter = Hash->nMembersUsed - HashPos;
+               ItemsAfter = Hash->nLookupTableItems - HashPos;
                /** make space were we can fill us in */
                if (ItemsAfter > 0)
                {
@@ -334,6 +347,7 @@ static void InsertHashItem(HashList *Hash,
        Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
        Hash->LookupTable[HashPos] = NewHashKey;
        Hash->nMembersUsed++;
+       Hash->nLookupTableItems++;
 }
 
 /**
@@ -350,7 +364,7 @@ static long FindInTaintedHash(HashList *Hash, long HashBinKey)
        if (Hash == NULL)
                return 0;
 
-       for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
+       for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
                if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
                        return SearchPos;
                }
@@ -375,10 +389,10 @@ static long FindInHash(HashList *Hash, long HashBinKey)
        if (Hash->tainted)
                return FindInTaintedHash(Hash, HashBinKey);
 
-       SearchPos = Hash->nMembersUsed / 2;
+       SearchPos = Hash->nLookupTableItems / 2;
        StepWidth = SearchPos / 2;
        while ((SearchPos > 0) && 
-              (SearchPos < Hash->nMembersUsed)) 
+              (SearchPos < Hash->nLookupTableItems)) 
        {
                /** Did we find it? */
                if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
@@ -400,7 +414,7 @@ static long FindInHash(HashList *Hash, long HashBinKey)
                                SearchPos --;
                        }
                        else {
-                               if ((SearchPos + 1 < Hash->nMembersUsed) && 
+                               if ((SearchPos + 1 < Hash->nLookupTableItems) && 
                                    (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
                                        return SearchPos;
                                SearchPos ++;
@@ -413,18 +427,31 @@ static long FindInHash(HashList *Hash, long HashBinKey)
 
 
 /**
- * @brief another hashing algorithm; treat it as just a pointer to long.
- * @param str Our pointer to the long value
+ * @brief another hashing algorithm; treat it as just a pointer to int.
+ * @param str Our pointer to the int value
  * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
  * \returns the calculated hash value
  */
-int Flathash(const char *str, long len)
+long Flathash(const char *str, long len)
 {
        if (len != sizeof (int))
                return 0;
        else return *(int*)str;
 }
 
+/**
+ * @brief another hashing algorithm; treat it as just a pointer to long.
+ * @param str Our pointer to the long value
+ * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
+ * \returns the calculated hash value
+ */
+long lFlathash(const char *str, long len)
+{
+       if (len != sizeof (long))
+               return 0;
+       else return *(long*)str;
+}
+
 /**
  * @brief private abstract wrapper around the hashing algorithm
  * @param HKey the hash string
@@ -515,7 +542,7 @@ int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
        HashBinKey = CalcHashKey(Hash, HKey, HKLen);
        HashAt = FindInHash(Hash, HashBinKey);
        if ((HashAt < 0) || /**< Not found at the lower edge? */
-           (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
+           (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
            (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
                *Data = NULL;
                return 0;
@@ -549,13 +576,13 @@ int GetHashKeys(HashList *Hash, char ***List)
        if (Hash->MyKeys != NULL)
                free (Hash->MyKeys);
 
-       Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
-       for (i=0; i < Hash->nMembersUsed; i++) {
+       Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
+       for (i=0; i < Hash->nLookupTableItems; i++) {
        
                Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
        }
        *List = (char**)Hash->MyKeys;
-       return Hash->nMembersUsed;
+       return Hash->nLookupTableItems;
 }
 
 /**
@@ -576,7 +603,7 @@ HashPos *GetNewHashPos(HashList *Hash, int StepWidth)
        else
                Ret->StepWidth = 1;
        if (Ret->StepWidth <  0) {
-               Ret->Position = Hash->nMembersUsed - 1;
+               Ret->Position = Hash->nLookupTableItems - 1;
        }
        else {
                Ret->Position = 0;
@@ -607,7 +634,7 @@ int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
        HashBinKey = CalcHashKey(Hash, HKey, HKLen);
        HashAt = FindInHash(Hash, HashBinKey);
        if ((HashAt < 0) || /**< Not found at the lower edge? */
-           (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
+           (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
            (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
                return 0;
        }
@@ -624,27 +651,50 @@ int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
  */
 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
 {
+       Payload *FreeMe;
        if (Hash == NULL)
                return 0;
 
+       /* if lockable, lock here */
        if ((Hash == NULL) || 
-           (At->Position >= Hash->nMembersUsed) || 
+           (At->Position >= Hash->nLookupTableItems) || 
            (At->Position < 0) ||
-           (At->Position > Hash->nMembersUsed))
-               return 0;
-       /** get rid of our payload */
-       if (Hash->Members[At->Position] != NULL)
+           (At->Position > Hash->nLookupTableItems))
        {
-               DeleteHashPayload(Hash->Members[At->Position]);
-               free(Hash->Members[At->Position]);
-               Hash->Members[At->Position] = NULL;
+               /* unlock... */
+               return 0;
        }
+
+       FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
+       Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
+
+
        /** delete our hashing data */
        if (Hash->LookupTable[At->Position] != NULL)
        {
                free(Hash->LookupTable[At->Position]->HashKey);
                free(Hash->LookupTable[At->Position]);
-               Hash->LookupTable[At->Position] = NULL;
+               if (At->Position < Hash->nLookupTableItems)
+               {
+                       memmove(&Hash->LookupTable[At->Position],
+                               &Hash->LookupTable[At->Position + 1],
+                               (Hash->nLookupTableItems - At->Position - 1) * 
+                               sizeof(HashKey*));
+
+                       Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
+               }
+               else 
+                       Hash->LookupTable[At->Position] = NULL;
+               Hash->nLookupTableItems--;
+       }
+       /* unlock... */
+
+
+       /** get rid of our payload */
+       if (FreeMe != NULL)
+       {
+               DeleteHashPayload(FreeMe);
+               free(FreeMe);
        }
        return 1;
 }
@@ -657,9 +707,9 @@ int DeleteEntryFromHash(HashList *Hash, HashPos *At)
 int GetHashPosCounter(HashList *Hash, HashPos *At)
 {
        if ((Hash == NULL) || 
-           (At->Position >= Hash->nMembersUsed) || 
+           (At->Position >= Hash->nLookupTableItems) || 
            (At->Position < 0) ||
-           (At->Position > Hash->nMembersUsed))
+           (At->Position > Hash->nLookupTableItems))
                return 0;
        return At->Position;
 }
@@ -680,6 +730,7 @@ void DeleteHashPos(HashPos **DelMe)
 /**
  * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
  * @param Hash your Hashlist to follow
+ * @param At the position to retrieve the Item from and move forward afterwards
  * @param HKLen returns Length of Hashkey Returned
  * @param HashKey returns the Hashkey corrosponding to HashPos
  * @param Data returns the Data found at HashPos
@@ -690,9 +741,9 @@ int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKe
        long PayloadPos;
 
        if ((Hash == NULL) || 
-           (At->Position >= Hash->nMembersUsed) || 
+           (At->Position >= Hash->nLookupTableItems) || 
            (At->Position < 0) ||
-           (At->Position > Hash->nMembersUsed))
+           (At->Position > Hash->nLookupTableItems))
                return 0;
        *HKLen = Hash->LookupTable[At->Position]->HKLen;
        *HashKey = Hash->LookupTable[At->Position]->HashKey;
@@ -708,6 +759,57 @@ int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKe
        return 1;
 }
 
+/**
+ * @brief Get the data located where HashPos Iterator points at
+ * @param Hash your Hashlist to follow
+ * @param At the position retrieve the data from
+ * @param HKLen returns Length of Hashkey Returned
+ * @param HashKey returns the Hashkey corrosponding to HashPos
+ * @param Data returns the Data found at HashPos
+ * \returns whether the item was found or not.
+ */
+int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
+{
+       long PayloadPos;
+
+       if ((Hash == NULL) || 
+           (At->Position >= Hash->nLookupTableItems) || 
+           (At->Position < 0) ||
+           (At->Position > Hash->nLookupTableItems))
+               return 0;
+       *HKLen = Hash->LookupTable[At->Position]->HKLen;
+       *HashKey = Hash->LookupTable[At->Position]->HashKey;
+       PayloadPos = Hash->LookupTable[At->Position]->Position;
+       *Data = Hash->Members[PayloadPos]->Data;
+
+       return 1;
+}
+
+/**
+ * @brief Move HashPos one forward
+ * @param Hash your Hashlist to follow
+ * @param At the position to move forward
+ * \returns whether there is a next item or not.
+ */
+int NextHashPos(HashList *Hash, HashPos *At)
+{
+       if ((Hash == NULL) || 
+           (At->Position >= Hash->nLookupTableItems) || 
+           (At->Position < 0) ||
+           (At->Position > Hash->nLookupTableItems))
+               return 0;
+
+       /* Position is NULL-Based, while Stepwidth is not... */
+       if ((At->Position % abs(At->StepWidth)) == 0)
+               At->Position += At->StepWidth;
+       else 
+               At->Position += ((At->Position) % abs(At->StepWidth)) * 
+                       (At->StepWidth / abs(At->StepWidth));
+       return !((At->Position >= Hash->nLookupTableItems) || 
+                (At->Position < 0) ||
+                (At->Position > Hash->nLookupTableItems));
+}
+
 /**
  * @brief Get the data located where At points to
  * note: you should prefer iterator operations instead of using me.
@@ -723,7 +825,7 @@ int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **
 
        if ((Hash == NULL) || 
            (At < 0) || 
-           (At > Hash->nMembersUsed))
+           (At >= Hash->nLookupTableItems))
                return 0;
        *HKLen = Hash->LookupTable[At]->HKLen;
        *HashKey = Hash->LookupTable[At]->HashKey;
@@ -732,6 +834,28 @@ int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **
        return 1;
 }
 
+/**
+ * @brief Get the data located where At points to
+ * note: you should prefer iterator operations instead of using me.
+ * @param Hash your Hashlist peek from
+ * @param HKLen returns Length of Hashkey Returned
+ * @param HashKey returns the Hashkey corrosponding to HashPos
+ * @param Data returns the Data found at HashPos
+ * \returns whether the item was found or not.
+ */
+/*
+long GetHashIDAt(HashList *Hash,long At)
+{
+       if ((Hash == NULL) || 
+           (At < 0) || 
+           (At > Hash->nLookupTableItems))
+               return 0;
+
+       return Hash->LookupTable[At]->Key;
+}
+*/
+
+
 /**
  * @brief sorting function for sorting the Hash alphabeticaly by their strings
  * @param Key1 first item
@@ -784,9 +908,9 @@ static int SortByHashKeys(const void *Key1, const void* Key2)
  */
 void SortByHashKey(HashList *Hash, int Order)
 {
-       if (Hash->nMembersUsed < 2)
+       if (Hash->nLookupTableItems < 2)
                return;
-       qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), 
+       qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), 
              (Order)?SortByKeys:SortByKeysRev);
        Hash->tainted = 1;
 }
@@ -799,9 +923,9 @@ void SortByHashKey(HashList *Hash, int Order)
 void SortByHashKeyStr(HashList *Hash)
 {
        Hash->tainted = 0;
-       if (Hash->nMembersUsed < 2)
+       if (Hash->nLookupTableItems < 2)
                return;
-       qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
+       qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
 }
 
 
@@ -823,9 +947,9 @@ const void *GetSearchPayload(const void *HashVoid)
  */
 void SortByPayload(HashList *Hash, CompareFunc SortBy)
 {
-       if (Hash->nMembersUsed < 2)
+       if (Hash->nLookupTableItems < 2)
                return;
-       qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
+       qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
        Hash->tainted = 1;
 }
 
@@ -845,15 +969,6 @@ void SortByPayload(HashList *Hash, CompareFunc SortBy)
  */
 
 
-/*
- * Generic function to free a pointer.  This can be used as a callback with the
- * hash table, even on systems where free() is defined as a macro or has had other
- * horrible things done to it.
- */
-void generic_free_handler(void *ptr) {
-       free(ptr);
-}
-
 /*
  * Generic function to free a reference.  
  * since a reference actualy isn't needed to be freed, do nothing.
@@ -871,3 +986,118 @@ int HashLittle(const void *key, size_t length) {
        return (int)hashlittle(key, length, 1);
 }
 
+
+/**
+ * \brief parses an MSet string into a list for later use
+ * \param MSetList List to be read from MSetStr
+ * \param MSetStr String containing the list
+ */
+int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
+{
+       const char *POS = NULL, *SetPOS = NULL;
+       StrBuf *OneSet;
+       HashList *ThisMSet;
+       long StartSet, EndSet;
+       long *pEndSet;
+       
+       *MSetList = NULL;
+       if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
+           return 0;
+           
+       OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
+
+       ThisMSet = NewHash(0, lFlathash);
+
+       *MSetList = (MSet*) ThisMSet;
+
+       /* an MSet is a coma separated value list. */
+       StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
+       do {
+               SetPOS = NULL;
+
+               /* One set may consist of two Numbers: Start + optional End */
+               StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
+               EndSet = 0; /* no range is our default. */
+               /* do we have an end (aka range?) */
+               if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
+               {
+                       if (*(SetPOS) == '*')
+                               EndSet = LONG_MAX; /* ranges with '*' go until infinity */
+                       else 
+                               /* in other cases, get the EndPoint */
+                               EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
+               }
+
+               pEndSet = (long*) malloc (sizeof(long));
+               *pEndSet = EndSet;
+
+               Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
+               /* if we don't have another, we're done. */
+               if (POS == StrBufNOTNULL)
+                       break;
+               StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
+       } while (1);
+       FreeStrBuf(&OneSet);
+
+       return 1;
+}
+
+/**
+ * \brief checks whether a message is inside a mset
+ * \param MSetList List to search for MsgNo
+ * \param MsgNo number to search in mset
+ */
+int IsInMSetList(MSet *MSetList, long MsgNo)
+{
+       /* basicaly we are a ... */
+       long MemberPosition;
+       HashList *Hash = (HashList*) MSetList;
+       long HashAt;
+       long EndAt;
+       long StartAt;
+
+       if (Hash == NULL)
+               return 0;
+       if (Hash->MemberSize == 0)
+               return 0;
+       /** first, find out were we could fit in... */
+       HashAt = FindInHash(Hash, MsgNo);
+       
+       /* we're below the first entry, so not found. */
+       if (HashAt < 0)
+               return 0;
+       /* upper edge? move to last item */
+       if (HashAt >= Hash->nMembersUsed)
+               HashAt = Hash->nMembersUsed - 1;
+       /* Match? then we got it. */
+       else if (Hash->LookupTable[HashAt]->Key == MsgNo)
+               return 1;
+       /* One above possible range start? we need to move to the lower one. */ 
+       else if ((HashAt > 0) && 
+                (Hash->LookupTable[HashAt]->Key > MsgNo))
+               HashAt -=1;
+
+       /* Fetch the actual data */
+       StartAt = Hash->LookupTable[HashAt]->Key;
+       MemberPosition = Hash->LookupTable[HashAt]->Position;
+       EndAt = *(long*) Hash->Members[MemberPosition]->Data;
+       if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
+               return 1;
+       /* no range? */
+       if (EndAt == 0)
+               return 0;
+       /* inside of range? */
+       if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
+               return 1;
+       return 0;
+}
+
+
+/**
+ * \brief frees a mset [redirects to @ref DeleteHash
+ * \param FreeMe to be free'd
+ */
+void DeleteMSet(MSet **FreeMe)
+{
+       DeleteHash((HashList**) FreeMe);
+}