]> code.citadel.org Git - citadel.git/blobdiff - libcitadel/lib/hash.c
* add new buffer class which handles concatenation of strings in dynamic buffers...
[citadel.git] / libcitadel / lib / hash.c
index 50c3e8d7a5de63b2dfd82ccf001e30e2b77344e1..1de53624da09f57355213fb1b6100bdb1263db85 100644 (file)
@@ -18,7 +18,7 @@ struct Payload {
 
 struct HashKey {
         /**
-        * \brief Hash key element; sorted by Keye
+        * \brief Hash key element; sorted by key
         */
        long Key;         /**< Numeric Hashkey comperator for hash sorting */
        long Position;    /**< Pointer to a Payload struct in the Payload Aray */
@@ -34,9 +34,11 @@ struct HashList {
        Payload **Members;     /**< Our Payload members. This fills up linear */
        HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
        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 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? */
 };
 
 struct HashPos {
@@ -46,6 +48,51 @@ struct HashPos {
        long Position;
 };
 
+
+/**
+ * \brief Iterate over the hash and call PrintEntry. 
+ * \param Hash your Hashlist structure
+ * \param Trans is called so you could for example print 'A:' if the next entries are like that.
+ *        Must be aware to receive NULL in both pointers.
+ * \param PrintEntry print entry one by one
+ * \returns the number of items printed
+ */
+int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
+{
+       int i;
+       void *Previous;
+       void *Next;
+       const char* KeyStr;
+
+       if (Hash == NULL)
+               return 0;
+
+       for (i=0; i < Hash->nMembersUsed; i++) {
+               if (i==0) {
+                       Previous = NULL;
+               }
+               else {
+                       if (Hash->LookupTable[i - 1] == NULL)
+                               Previous = NULL;
+                       else
+                               Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
+               }
+               if (Hash->LookupTable[i] == NULL) {
+                       KeyStr = "";
+                       Next = NULL;
+               }
+               else {
+                       Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
+                       KeyStr = Hash->LookupTable[i]->HashKey;
+               }
+
+               Trans(Previous, Next, i % 2);
+               PrintEntry(KeyStr, Next, i % 2);
+       }
+       return i;
+}
+
+
 /**
  * \brief verify the contents of a hash list; here for debugging purposes.
  * \param Hash your Hashlist structure
@@ -53,13 +100,17 @@ struct HashPos {
  * \param Second Functionpointer to allow you to print your payload
  * \returns 0
  */
-int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
+int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
 {
        const char *foo;
        const char *bar;
        const char *bla = "";
        long key;
        long i;
+
+       if (Hash == NULL)
+               return 0;
+
        if (Hash->MyKeys != NULL)
                free (Hash->MyKeys);
 
@@ -81,8 +132,12 @@ int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
                        foo = Hash->LookupTable[i]->HashKey;
                        if (First != NULL)
                                bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
+                       else 
+                               bar = "";
                        if (Second != NULL)
                                bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
+                       else
+                               bla = "";
                }
 #ifdef DEBUG
                printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
@@ -99,7 +154,7 @@ int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
  * \brief instanciate a new hashlist
  * \returns the newly allocated list. 
  */
-HashList *NewHash(void) 
+HashList *NewHash(int Uniq, HashFunc F)
 {
        HashList *NewList;
        NewList = malloc (sizeof(HashList));
@@ -113,10 +168,19 @@ HashList *NewHash(void)
 
        NewList->MemberSize = 100;
        NewList->tainted = 0;
+        NewList->uniq = Uniq;
+       NewList->Algorithm = F;
 
        return NewList;
 }
 
+int GetCount(HashList *Hash)
+{
+       if(Hash==NULL) return 0;
+       return Hash->nMembersUsed;
+}
+
+
 /**
  * \brief private destructor for one hash element.
  * \param Data an element to free using the user provided destructor, or just plain free
@@ -168,6 +232,36 @@ void DeleteHash(HashList **Hash)
        *Hash = NULL;
 }
 
+/**
+ * \brief Private function to increase the hash size.
+ * \param Hash the Hasharray to increase
+ */
+static void IncreaseHashSize(HashList *Hash)
+{
+       /* Ok, Our space is used up. Double the available space. */
+       Payload **NewPayloadArea;
+       HashKey **NewTable;
+       
+       if (Hash == NULL)
+               return ;
+
+       /** double our payload area */
+       NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
+       memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
+       memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
+       free(Hash->Members);
+       Hash->Members = NewPayloadArea;
+       
+       /** double our hashtable area */
+       NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
+       memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
+       memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
+       free(Hash->LookupTable);
+       Hash->LookupTable = NewTable;
+       
+       Hash->MemberSize *= 2;
+}
+
 
 /**
  * \brief private function to add a new item to / replace an existing in -  the hashlist
@@ -182,7 +276,7 @@ void DeleteHash(HashList **Hash)
 static void InsertHashItem(HashList *Hash, 
                           long HashPos, 
                           long HashBinKey, 
-                          char *HashKeyStr, 
+                          const char *HashKeyStr, 
                           long HKLen, 
                           void *Data,
                           DeleteHashDataFunc Destructor)
@@ -190,28 +284,12 @@ static void InsertHashItem(HashList *Hash,
        Payload *NewPayloadItem;
        HashKey *NewHashKey;
 
+       if (Hash == NULL)
+               return;
+
        if (Hash->nMembersUsed >= Hash->MemberSize)
-       {
-               /* Ok, Our space is used up. Double the available space. */
-               Payload **NewPayloadArea;
-               HashKey **NewTable;
-
-               /** double our payload area */
-               NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
-               memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
-               memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
-               free(Hash->Members);
-               Hash->Members = NewPayloadArea;
-
-               /** double our hashtable area */
-               NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
-               memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
-               memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
-               free(Hash->LookupTable);
-               Hash->LookupTable = NewTable;
-
-               Hash->MemberSize *= 2;
-       }
+               IncreaseHashSize (Hash);
+
        /** Arrange the payload */
        NewPayloadItem = (Payload*) malloc (sizeof(Payload));
        NewPayloadItem->Data = Data;
@@ -228,16 +306,14 @@ static void InsertHashItem(HashList *Hash,
        /** but if we should be sorted into a specific place... */
        if ((Hash->nMembersUsed != 0) && 
            (HashPos != Hash->nMembersUsed) ) {
-               long InsertAt;
                long ItemsAfter;
 
                ItemsAfter = Hash->nMembersUsed - HashPos;
-               InsertAt = HashPos;
                /** make space were we can fill us in */
                if (ItemsAfter > 0)
                {
-                       memmove(&Hash->LookupTable[InsertAt + 1],
-                               &Hash->LookupTable[InsertAt],
+                       memmove(&Hash->LookupTable[HashPos + 1],
+                               &Hash->LookupTable[HashPos],
                                ItemsAfter * sizeof(HashKey*));
                } 
        }
@@ -258,6 +334,9 @@ static long FindInTaintedHash(HashList *Hash, long HashBinKey)
 {
        long SearchPos;
 
+       if (Hash == NULL)
+               return 0;
+
        for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
                if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
                        return SearchPos;
@@ -277,6 +356,9 @@ static long FindInHash(HashList *Hash, long HashBinKey)
        long SearchPos;
        long StepWidth;
 
+       if (Hash == NULL)
+               return 0;
+
        if (Hash->tainted)
                return FindInTaintedHash(Hash, HashBinKey);
 
@@ -322,9 +404,15 @@ static long FindInHash(HashList *Hash, long HashBinKey)
  * \param HKLen length of HKey
  * \returns the calculated hash value
  */
-inline static long CalcHashKey (char *HKey, long HKLen)
+inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
 {
-       return hashlittle(HKey, HKLen, 9283457);
+       if (Hash == NULL)
+               return 0;
+
+       if (Hash->Algorithm == NULL)
+               return hashlittle(HKey, HKLen, 9283457);
+       else
+               return Hash->Algorithm(HKey, HKLen);
 }
 
 
@@ -336,32 +424,43 @@ inline static long CalcHashKey (char *HKey, long HKLen)
  * \param Data the payload you want to associate with HKey
  * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
  */
-void Put(HashList *Hash, char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
+void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
 {
        long HashBinKey;
        long HashAt;
 
+       if (Hash == NULL)
+               return;
+
        /** first, find out were we could fit in... */
-       HashBinKey = CalcHashKey(HKey, HKLen);
+       HashBinKey = CalcHashKey(Hash, HKey, HKLen);
        HashAt = FindInHash(Hash, HashBinKey);
 
+       if (HashAt >= Hash->MemberSize)
+               IncreaseHashSize (Hash);
+
        /** oh, we're brand new... */
-       if (Hash->LookupTable[HashAt] == NULL){
+       if (Hash->LookupTable[HashAt] == NULL) {
                InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
        }/** Insert After? */
        else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
                InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
        }/** Insert before? */
        else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
-               InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);              
+               InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
        }
        else { /** Ok, we have a colision. replace it. */
-               long PayloadPos;
-
-               PayloadPos = Hash->LookupTable[HashAt]->Position;
-               DeleteHashPayload(Hash->Members[PayloadPos]);
-               Hash->Members[PayloadPos]->Data = Data;
-               Hash->Members[PayloadPos]->Destructor = DeleteIt;
+               if (Hash->uniq) {
+                       long PayloadPos;
+                       
+                       PayloadPos = Hash->LookupTable[HashAt]->Position;
+                       DeleteHashPayload(Hash->Members[PayloadPos]);
+                       Hash->Members[PayloadPos]->Data = Data;
+                       Hash->Members[PayloadPos]->Destructor = DeleteIt;
+               }
+               else {
+                       InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
+               }
        }
 }
 
@@ -378,8 +477,15 @@ int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
        long HashBinKey;
        long HashAt;
 
+       if (Hash == NULL)
+               return 0;
+
+       if (HKLen <= 0) {
+               *Data = NULL;
+               return  0;
+       }
        /** first, find out were we could be... */
-       HashBinKey = CalcHashKey((char*)HKey, HKLen);
+       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? */
@@ -411,6 +517,8 @@ int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
 int GetHashKeys(HashList *Hash, char ***List)
 {
        long i;
+       if (Hash == NULL)
+               return 0;
        if (Hash->MyKeys != NULL)
                free (Hash->MyKeys);
 
@@ -441,8 +549,11 @@ HashPos *GetNewHashPos(void)
  */
 void DeleteHashPos(HashPos **DelMe)
 {
-       free(*DelMe);
-       *DelMe = NULL;
+       if (*DelMe != NULL)
+       {
+               free(*DelMe);
+               *DelMe = NULL;
+       }
 }
 
 
@@ -458,7 +569,7 @@ int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, char **HashKey, voi
 {
        long PayloadPos;
 
-       if (Hash->nMembersUsed <= At->Position)
+       if ((Hash == NULL) || (Hash->nMembersUsed <= At->Position))
                return 0;
        *HKLen = Hash->LookupTable[At->Position]->HKLen;
        *HashKey = Hash->LookupTable[At->Position]->HashKey;
@@ -482,6 +593,20 @@ static int SortByKeys(const void *Key1, const void* Key2)
        return strcasecmp(HKey1->HashKey, HKey2->HashKey);
 }
 
+/**
+ * \brief sorting function for sorting the Hash alphabeticaly reverse by their strings
+ * \param Key1 first item
+ * \param Key2 second item
+ */
+static int SortByKeysRev(const void *Key1, const void* Key2)
+{
+       HashKey *HKey1, *HKey2;
+       HKey1 = *(HashKey**) Key1;
+       HKey2 = *(HashKey**) Key2;
+
+       return strcasecmp(HKey2->HashKey, HKey1->HashKey);
+}
+
 /**
  * \brief sorting function to regain hash-sequence and revert tainted status
  * \param Key1 first item
@@ -502,12 +627,14 @@ static int SortByHashKeys(const void *Key1, const void* Key2)
  * Caution: This taints the hashlist, so accessing it later 
  * will be significantly slower! You can un-taint it by SortByHashKeyStr
  * \param Hash the list to sort
+ * \param Order 0/1 Forward/Backward
  */
-void SortByHashKey(HashList *Hash)
+void SortByHashKey(HashList *Hash, int Order)
 {
        if (Hash->nMembersUsed < 2)
                return;
-       qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByKeys);
+       qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), 
+             (Order)?SortByKeys:SortByKeysRev);
        Hash->tainted = 1;
 }
 
@@ -563,3 +690,16 @@ void SortByPayload(HashList *Hash, CompareFunc SortBy)
  *      return strcmp (a, b);
  * }
  */
+
+
+/*
+ * 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);
+}
+
+
+