6 #include "libcitadel.h"
9 typedef struct Payload Payload;
13 * \brief Hash Payload storage Structure; filled in linear.
15 void *Data; /**< the Data belonging to this storage */
16 DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
21 * \brief Hash key element; sorted by key
23 long Key; /**< Numeric Hashkey comperator for hash sorting */
24 long Position; /**< Pointer to a Payload struct in the Payload Aray */
25 char *HashKey; /**< the Plaintext Hashkey */
26 long HKLen; /**< length of the Plaintext Hashkey */
27 Payload *PL; /**< pointer to our payload for sorting */
32 * \brief Hash structure; holds arrays of Hashkey and Payload.
34 Payload **Members; /**< Our Payload members. This fills up linear */
35 HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
36 char **MyKeys; /**< this keeps the members for a call of GetHashKeys */
37 HashFunc Algorithm; /**< should we use an alternating algorithm to calc the hash values? */
38 long nMembersUsed; /**< how many pointers inside of the array are used? */
39 long MemberSize; /**< how big is Members and LookupTable? */
40 long tainted; /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
41 long uniq; /**< are the keys going to be uniq? */
46 * \brief Anonymous Hash Iterator Object. used for traversing the whole array from outside
52 * \brief verify the contents of a hash list; here for debugging purposes.
53 * \param Hash your Hashlist structure
54 * \param First Functionpointer to allow you to print your payload
55 * \param Second Functionpointer to allow you to print your payload
58 int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
65 if (Hash->MyKeys != NULL)
68 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
70 printf("----------------------------------\n");
72 for (i=0; i < Hash->nMembersUsed; i++) {
74 if (Hash->LookupTable[i] == NULL)
82 key = Hash->LookupTable[i]->Key;
83 foo = Hash->LookupTable[i]->HashKey;
85 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
87 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
90 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
94 printf("----------------------------------\n");
101 * \brief instanciate a new hashlist
102 * \returns the newly allocated list.
104 HashList *NewHash(int Uniq, HashFunc F)
107 NewList = malloc (sizeof(HashList));
108 memset(NewList, 0, sizeof(HashList));
110 NewList->Members = malloc(sizeof(Payload*) * 100);
111 memset(NewList->Members, 0, sizeof(Payload*) * 100);
113 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
114 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
116 NewList->MemberSize = 100;
117 NewList->tainted = 0;
118 NewList->uniq = Uniq;
119 NewList->Algorithm = F;
125 * \brief private destructor for one hash element.
126 * \param Data an element to free using the user provided destructor, or just plain free
128 static void DeleteHashPayload (Payload *Data)
130 /** do we have a destructor for our payload? */
131 if (Data->Destructor)
132 Data->Destructor(Data->Data);
138 * \brief destroy a hashlist and all of its members
139 * \param Hash Hash to destroy. Is NULL'ed so you are shure its done.
141 void DeleteHash(HashList **Hash)
149 for (i=0; i < FreeMe->nMembersUsed; i++)
151 /** get rid of our payload */
152 if (FreeMe->Members[i] != NULL)
154 DeleteHashPayload(FreeMe->Members[i]);
155 free(FreeMe->Members[i]);
157 /** delete our hashing data */
158 if (FreeMe->LookupTable[i] != NULL)
160 free(FreeMe->LookupTable[i]->HashKey);
161 free(FreeMe->LookupTable[i]);
164 /** now, free our arrays... */
165 free(FreeMe->LookupTable);
166 free(FreeMe->Members);
167 /** did s.b. want an array of our keys? free them. */
168 if (FreeMe->MyKeys != NULL)
169 free(FreeMe->MyKeys);
170 /** buye bye cruel world. */
176 * \brief Private function to increase the hash size.
177 * \param Hash the Hasharray to increase
179 static void IncreaseHashSize(HashList *Hash)
181 /* Ok, Our space is used up. Double the available space. */
182 Payload **NewPayloadArea;
185 /** double our payload area */
186 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
187 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
188 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
190 Hash->Members = NewPayloadArea;
192 /** double our hashtable area */
193 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
194 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
195 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
196 free(Hash->LookupTable);
197 Hash->LookupTable = NewTable;
199 Hash->MemberSize *= 2;
204 * \brief private function to add a new item to / replace an existing in - the hashlist
205 * if the hash list is full, its re-alloced with double size.
206 * \parame Hash our hashlist to manipulate
207 * \param HashPos where should we insert / replace?
208 * \param HashKeyStr the Hash-String
209 * \param HKLen length of HashKeyStr
210 * \param Data your Payload to add
211 * \param Destructor Functionpointer to free Data. if NULL, default free() is used.
213 static void InsertHashItem(HashList *Hash,
216 const char *HashKeyStr,
219 DeleteHashDataFunc Destructor)
221 Payload *NewPayloadItem;
224 if (Hash->nMembersUsed >= Hash->MemberSize)
225 IncreaseHashSize (Hash);
227 /** Arrange the payload */
228 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
229 NewPayloadItem->Data = Data;
230 NewPayloadItem->Destructor = Destructor;
231 /** Arrange the hashkey */
232 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
233 NewHashKey->HashKey = (char *) malloc (HKLen + 1);
234 NewHashKey->HKLen = HKLen;
235 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
236 NewHashKey->Key = HashBinKey;
237 NewHashKey->PL = NewPayloadItem;
238 /** our payload is queued at the end... */
239 NewHashKey->Position = Hash->nMembersUsed;
240 /** but if we should be sorted into a specific place... */
241 if ((Hash->nMembersUsed != 0) &&
242 (HashPos != Hash->nMembersUsed) ) {
246 ItemsAfter = Hash->nMembersUsed - HashPos;
248 /** make space were we can fill us in */
251 memmove(&Hash->LookupTable[InsertAt + 1],
252 &Hash->LookupTable[InsertAt],
253 ItemsAfter * sizeof(HashKey*));
257 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
258 Hash->LookupTable[HashPos] = NewHashKey;
259 Hash->nMembersUsed++;
263 * \brief if the user has tainted the hash, but wants to insert / search items by their key
264 * we need to search linear through the array. You have been warned that this will take more time!
265 * \param Hash Our Hash to manipulate
266 * \param HashBinKey the Hash-Number to lookup.
267 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
269 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
273 for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
274 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
282 * \brief Private function to lookup the Item / the closest position to put it in
283 * \param Hash Our Hash to manipulate
284 * \param HashBinKey the Hash-Number to lookup.
285 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
287 static long FindInHash(HashList *Hash, long HashBinKey)
293 return FindInTaintedHash(Hash, HashBinKey);
295 SearchPos = Hash->nMembersUsed / 2;
296 StepWidth = SearchPos / 2;
297 while ((SearchPos > 0) &&
298 (SearchPos < Hash->nMembersUsed))
300 /** Did we find it? */
301 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
304 /** are we Aproximating in big steps? */
306 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
307 SearchPos -= StepWidth;
309 SearchPos += StepWidth;
312 else { /** We are right next to our target, within 4 positions */
313 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
314 if ((SearchPos > 0) &&
315 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
320 if ((SearchPos + 1 < Hash->nMembersUsed) &&
321 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
332 * \brief private abstract wrapper around the hashing algorithm
333 * \param HKey the hash string
334 * \param HKLen length of HKey
335 * \returns the calculated hash value
337 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
339 if (Hash->Algorithm == NULL)
340 return hashlittle(HKey, HKLen, 9283457);
342 return Hash->Algorithm(HKey, HKLen);
347 * \brief Add a new / Replace an existing item in the Hash
348 * \param HashList the list to manipulate
349 * \param HKey the hash-string to store Data under
350 * \param HKeyLen Length of HKey
351 * \param Data the payload you want to associate with HKey
352 * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
354 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
359 /** first, find out were we could fit in... */
360 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
361 HashAt = FindInHash(Hash, HashBinKey);
363 if (HashAt >= Hash->MemberSize)
364 IncreaseHashSize (Hash);
366 /** oh, we're brand new... */
367 if (Hash->LookupTable[HashAt] == NULL) {
368 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
369 }/** Insert After? */
370 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
371 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
372 }/** Insert before? */
373 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
374 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
376 else { /** Ok, we have a colision. replace it. */
380 PayloadPos = Hash->LookupTable[HashAt]->Position;
381 DeleteHashPayload(Hash->Members[PayloadPos]);
382 Hash->Members[PayloadPos]->Data = Data;
383 Hash->Members[PayloadPos]->Destructor = DeleteIt;
386 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
392 * \brief Lookup the Data associated with HKey
393 * \param Hash the Hashlist to search in
394 * \param HKey the hashkey to look up
395 * \param HKLen length of HKey
396 * \param Data returns the Data associated with HKey
397 * \returns 0 if not found, 1 if.
399 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
408 /** first, find out were we could be... */
409 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
410 HashAt = FindInHash(Hash, HashBinKey);
411 if ((HashAt < 0) || /**< Not found at the lower edge? */
412 (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
413 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
417 else { /** GOTCHA! */
420 MemberPosition = Hash->LookupTable[HashAt]->Position;
421 *Data = Hash->Members[MemberPosition]->Data;
427 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
433 * \brief get the Keys present in this hash, simila to array_keys() in PHP
434 * Attention: List remains to Hash! don't modify or free it!
435 * \param Hash Your Hashlist to extract the keys from
436 * \param List returns the list of hashkeys stored in Hash
438 int GetHashKeys(HashList *Hash, char ***List)
441 if (Hash->MyKeys != NULL)
444 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
445 for (i=0; i < Hash->nMembersUsed; i++) {
447 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
449 *List = (char**)Hash->MyKeys;
450 return Hash->nMembersUsed;
454 * \brief creates a hash-linear iterator object
455 * \returns the hash iterator
457 HashPos *GetNewHashPos(void)
461 Ret = (HashPos*)malloc(sizeof(HashPos));
467 * \brief frees a linear hash iterator
469 void DeleteHashPos(HashPos **DelMe)
477 * \brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
478 * \param Hash your Hashlist to follow
479 * \param HKLen returns Length of Hashkey Returned
480 * \param HashKey returns the Hashkey corrosponding to HashPos
481 * \param Data returns the Data found at HashPos
482 * \returns whether the item was found or not.
484 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, char **HashKey, void **Data)
488 if (Hash->nMembersUsed <= At->Position)
490 *HKLen = Hash->LookupTable[At->Position]->HKLen;
491 *HashKey = Hash->LookupTable[At->Position]->HashKey;
492 PayloadPos = Hash->LookupTable[At->Position]->Position;
493 *Data = Hash->Members[PayloadPos]->Data;
499 * \brief sorting function for sorting the Hash alphabeticaly by their strings
500 * \param Key1 first item
501 * \param Key2 second item
503 static int SortByKeys(const void *Key1, const void* Key2)
505 HashKey *HKey1, *HKey2;
506 HKey1 = *(HashKey**) Key1;
507 HKey2 = *(HashKey**) Key2;
509 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
513 * \brief sorting function to regain hash-sequence and revert tainted status
514 * \param Key1 first item
515 * \param Key2 second item
517 static int SortByHashKeys(const void *Key1, const void* Key2)
519 HashKey *HKey1, *HKey2;
520 HKey1 = *(HashKey**) Key1;
521 HKey2 = *(HashKey**) Key2;
523 return HKey1->Key > HKey2->Key;
528 * \brief sort the hash alphabeticaly by their keys.
529 * Caution: This taints the hashlist, so accessing it later
530 * will be significantly slower! You can un-taint it by SortByHashKeyStr
531 * \param Hash the list to sort
533 void SortByHashKey(HashList *Hash)
535 if (Hash->nMembersUsed < 2)
537 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByKeys);
542 * \brief sort the hash by their keys (so it regains untainted state).
543 * this will result in the sequence the hashing allgorithm produces it by default.
544 * \param Hash the list to sort
546 void SortByHashKeyStr(HashList *Hash)
549 if (Hash->nMembersUsed < 2)
551 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
556 * \brief gives user sort routines access to the hash payload
557 * \param Searchentry to retrieve Data to
558 * \returns Data belonging to HashVoid
560 const void *GetSearchPayload(const void *HashVoid)
562 return (*(HashKey**)HashVoid)->PL->Data;
566 * \brief sort the hash by your sort function. see the following sample.
567 * this will result in the sequence the hashing allgorithm produces it by default.
568 * \param Hash the list to sort
569 * \param SortBy Sortfunction; see below how to implement this
571 void SortByPayload(HashList *Hash, CompareFunc SortBy)
573 if (Hash->nMembersUsed < 2)
575 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
583 * given you've put char * into your hash as a payload, a sort function might
585 * int SortByChar(const void* First, const void* Second)
588 * a = (char*) GetSearchPayload(First);
589 * b = (char*) GetSearchPayload(Second);
590 * return strcmp (a, b);