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
53 * \brief Iterate over the hash and call PrintEntry.
54 * \param Hash your Hashlist structure
55 * \param Trans is called so you could for example print 'A:' if the next entries are like that.
56 * Must be aware to receive NULL in both pointers.
57 * \param PrintEntry print entry one by one
58 * \returns the number of items printed
60 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
70 for (i=0; i < Hash->nMembersUsed; i++) {
75 if (Hash->LookupTable[i - 1] == NULL)
78 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
80 if (Hash->LookupTable[i] == NULL) {
85 Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
86 KeyStr = Hash->LookupTable[i]->HashKey;
89 Trans(Previous, Next, i % 2);
90 PrintEntry(KeyStr, Next, i % 2);
97 * \brief verify the contents of a hash list; here for debugging purposes.
98 * \param Hash your Hashlist structure
99 * \param First Functionpointer to allow you to print your payload
100 * \param Second Functionpointer to allow you to print your payload
103 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
107 const char *bla = "";
114 if (Hash->MyKeys != NULL)
117 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
119 printf("----------------------------------\n");
121 for (i=0; i < Hash->nMembersUsed; i++) {
123 if (Hash->LookupTable[i] == NULL)
131 key = Hash->LookupTable[i]->Key;
132 foo = Hash->LookupTable[i]->HashKey;
134 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
138 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
143 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
147 printf("----------------------------------\n");
154 * \brief instanciate a new hashlist
155 * \returns the newly allocated list.
157 HashList *NewHash(int Uniq, HashFunc F)
160 NewList = malloc (sizeof(HashList));
161 memset(NewList, 0, sizeof(HashList));
163 NewList->Members = malloc(sizeof(Payload*) * 100);
164 memset(NewList->Members, 0, sizeof(Payload*) * 100);
166 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
167 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
169 NewList->MemberSize = 100;
170 NewList->tainted = 0;
171 NewList->uniq = Uniq;
172 NewList->Algorithm = F;
177 int GetCount(HashList *Hash)
179 if(Hash==NULL) return 0;
180 return Hash->nMembersUsed;
185 * \brief private destructor for one hash element.
186 * \param Data an element to free using the user provided destructor, or just plain free
188 static void DeleteHashPayload (Payload *Data)
190 /** do we have a destructor for our payload? */
191 if (Data->Destructor)
192 Data->Destructor(Data->Data);
198 * \brief destroy a hashlist and all of its members
199 * \param Hash Hash to destroy. Is NULL'ed so you are shure its done.
201 void DeleteHash(HashList **Hash)
209 for (i=0; i < FreeMe->nMembersUsed; i++)
211 /** get rid of our payload */
212 if (FreeMe->Members[i] != NULL)
214 DeleteHashPayload(FreeMe->Members[i]);
215 free(FreeMe->Members[i]);
217 /** delete our hashing data */
218 if (FreeMe->LookupTable[i] != NULL)
220 free(FreeMe->LookupTable[i]->HashKey);
221 free(FreeMe->LookupTable[i]);
224 /** now, free our arrays... */
225 free(FreeMe->LookupTable);
226 free(FreeMe->Members);
227 /** did s.b. want an array of our keys? free them. */
228 if (FreeMe->MyKeys != NULL)
229 free(FreeMe->MyKeys);
230 /** buye bye cruel world. */
236 * \brief Private function to increase the hash size.
237 * \param Hash the Hasharray to increase
239 static void IncreaseHashSize(HashList *Hash)
241 /* Ok, Our space is used up. Double the available space. */
242 Payload **NewPayloadArea;
248 /** double our payload area */
249 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
250 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
251 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
253 Hash->Members = NewPayloadArea;
255 /** double our hashtable area */
256 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
257 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
258 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
259 free(Hash->LookupTable);
260 Hash->LookupTable = NewTable;
262 Hash->MemberSize *= 2;
267 * \brief private function to add a new item to / replace an existing in - the hashlist
268 * if the hash list is full, its re-alloced with double size.
269 * \parame Hash our hashlist to manipulate
270 * \param HashPos where should we insert / replace?
271 * \param HashKeyStr the Hash-String
272 * \param HKLen length of HashKeyStr
273 * \param Data your Payload to add
274 * \param Destructor Functionpointer to free Data. if NULL, default free() is used.
276 static void InsertHashItem(HashList *Hash,
279 const char *HashKeyStr,
282 DeleteHashDataFunc Destructor)
284 Payload *NewPayloadItem;
290 if (Hash->nMembersUsed >= Hash->MemberSize)
291 IncreaseHashSize (Hash);
293 /** Arrange the payload */
294 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
295 NewPayloadItem->Data = Data;
296 NewPayloadItem->Destructor = Destructor;
297 /** Arrange the hashkey */
298 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
299 NewHashKey->HashKey = (char *) malloc (HKLen + 1);
300 NewHashKey->HKLen = HKLen;
301 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
302 NewHashKey->Key = HashBinKey;
303 NewHashKey->PL = NewPayloadItem;
304 /** our payload is queued at the end... */
305 NewHashKey->Position = Hash->nMembersUsed;
306 /** but if we should be sorted into a specific place... */
307 if ((Hash->nMembersUsed != 0) &&
308 (HashPos != Hash->nMembersUsed) ) {
311 ItemsAfter = Hash->nMembersUsed - HashPos;
312 /** make space were we can fill us in */
315 memmove(&Hash->LookupTable[HashPos + 1],
316 &Hash->LookupTable[HashPos],
317 ItemsAfter * sizeof(HashKey*));
321 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
322 Hash->LookupTable[HashPos] = NewHashKey;
323 Hash->nMembersUsed++;
327 * \brief if the user has tainted the hash, but wants to insert / search items by their key
328 * we need to search linear through the array. You have been warned that this will take more time!
329 * \param Hash Our Hash to manipulate
330 * \param HashBinKey the Hash-Number to lookup.
331 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
333 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
340 for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
341 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
349 * \brief Private function to lookup the Item / the closest position to put it in
350 * \param Hash Our Hash to manipulate
351 * \param HashBinKey the Hash-Number to lookup.
352 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
354 static long FindInHash(HashList *Hash, long HashBinKey)
363 return FindInTaintedHash(Hash, HashBinKey);
365 SearchPos = Hash->nMembersUsed / 2;
366 StepWidth = SearchPos / 2;
367 while ((SearchPos > 0) &&
368 (SearchPos < Hash->nMembersUsed))
370 /** Did we find it? */
371 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
374 /** are we Aproximating in big steps? */
376 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
377 SearchPos -= StepWidth;
379 SearchPos += StepWidth;
382 else { /** We are right next to our target, within 4 positions */
383 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
384 if ((SearchPos > 0) &&
385 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
390 if ((SearchPos + 1 < Hash->nMembersUsed) &&
391 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
402 * \brief private abstract wrapper around the hashing algorithm
403 * \param HKey the hash string
404 * \param HKLen length of HKey
405 * \returns the calculated hash value
407 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
412 if (Hash->Algorithm == NULL)
413 return hashlittle(HKey, HKLen, 9283457);
415 return Hash->Algorithm(HKey, HKLen);
420 * \brief Add a new / Replace an existing item in the Hash
421 * \param HashList the list to manipulate
422 * \param HKey the hash-string to store Data under
423 * \param HKeyLen Length of HKey
424 * \param Data the payload you want to associate with HKey
425 * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
427 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
435 /** first, find out were we could fit in... */
436 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
437 HashAt = FindInHash(Hash, HashBinKey);
439 if (HashAt >= Hash->MemberSize)
440 IncreaseHashSize (Hash);
442 /** oh, we're brand new... */
443 if (Hash->LookupTable[HashAt] == NULL) {
444 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
445 }/** Insert After? */
446 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
447 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
448 }/** Insert before? */
449 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
450 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
452 else { /** Ok, we have a colision. replace it. */
456 PayloadPos = Hash->LookupTable[HashAt]->Position;
457 DeleteHashPayload(Hash->Members[PayloadPos]);
458 Hash->Members[PayloadPos]->Data = Data;
459 Hash->Members[PayloadPos]->Destructor = DeleteIt;
462 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
468 * \brief Lookup the Data associated with HKey
469 * \param Hash the Hashlist to search in
470 * \param HKey the hashkey to look up
471 * \param HKLen length of HKey
472 * \param Data returns the Data associated with HKey
473 * \returns 0 if not found, 1 if.
475 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
487 /** first, find out were we could be... */
488 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
489 HashAt = FindInHash(Hash, HashBinKey);
490 if ((HashAt < 0) || /**< Not found at the lower edge? */
491 (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
492 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
496 else { /** GOTCHA! */
499 MemberPosition = Hash->LookupTable[HashAt]->Position;
500 *Data = Hash->Members[MemberPosition]->Data;
506 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
512 * \brief get the Keys present in this hash, simila to array_keys() in PHP
513 * Attention: List remains to Hash! don't modify or free it!
514 * \param Hash Your Hashlist to extract the keys from
515 * \param List returns the list of hashkeys stored in Hash
517 int GetHashKeys(HashList *Hash, char ***List)
522 if (Hash->MyKeys != NULL)
525 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
526 for (i=0; i < Hash->nMembersUsed; i++) {
528 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
530 *List = (char**)Hash->MyKeys;
531 return Hash->nMembersUsed;
535 * \brief creates a hash-linear iterator object
536 * \returns the hash iterator
538 HashPos *GetNewHashPos(void)
542 Ret = (HashPos*)malloc(sizeof(HashPos));
548 * \brief frees a linear hash iterator
550 void DeleteHashPos(HashPos **DelMe)
561 * \brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
562 * \param Hash your Hashlist to follow
563 * \param HKLen returns Length of Hashkey Returned
564 * \param HashKey returns the Hashkey corrosponding to HashPos
565 * \param Data returns the Data found at HashPos
566 * \returns whether the item was found or not.
568 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
572 if ((Hash == NULL) || (Hash->nMembersUsed <= At->Position))
574 *HKLen = Hash->LookupTable[At->Position]->HKLen;
575 *HashKey = Hash->LookupTable[At->Position]->HashKey;
576 PayloadPos = Hash->LookupTable[At->Position]->Position;
577 *Data = Hash->Members[PayloadPos]->Data;
583 * \brief sorting function for sorting the Hash alphabeticaly by their strings
584 * \param Key1 first item
585 * \param Key2 second item
587 static int SortByKeys(const void *Key1, const void* Key2)
589 HashKey *HKey1, *HKey2;
590 HKey1 = *(HashKey**) Key1;
591 HKey2 = *(HashKey**) Key2;
593 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
597 * \brief sorting function for sorting the Hash alphabeticaly reverse by their strings
598 * \param Key1 first item
599 * \param Key2 second item
601 static int SortByKeysRev(const void *Key1, const void* Key2)
603 HashKey *HKey1, *HKey2;
604 HKey1 = *(HashKey**) Key1;
605 HKey2 = *(HashKey**) Key2;
607 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
611 * \brief sorting function to regain hash-sequence and revert tainted status
612 * \param Key1 first item
613 * \param Key2 second item
615 static int SortByHashKeys(const void *Key1, const void* Key2)
617 HashKey *HKey1, *HKey2;
618 HKey1 = *(HashKey**) Key1;
619 HKey2 = *(HashKey**) Key2;
621 return HKey1->Key > HKey2->Key;
626 * \brief sort the hash alphabeticaly by their keys.
627 * Caution: This taints the hashlist, so accessing it later
628 * will be significantly slower! You can un-taint it by SortByHashKeyStr
629 * \param Hash the list to sort
630 * \param Order 0/1 Forward/Backward
632 void SortByHashKey(HashList *Hash, int Order)
634 if (Hash->nMembersUsed < 2)
636 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*),
637 (Order)?SortByKeys:SortByKeysRev);
642 * \brief sort the hash by their keys (so it regains untainted state).
643 * this will result in the sequence the hashing allgorithm produces it by default.
644 * \param Hash the list to sort
646 void SortByHashKeyStr(HashList *Hash)
649 if (Hash->nMembersUsed < 2)
651 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
656 * \brief gives user sort routines access to the hash payload
657 * \param Searchentry to retrieve Data to
658 * \returns Data belonging to HashVoid
660 const void *GetSearchPayload(const void *HashVoid)
662 return (*(HashKey**)HashVoid)->PL->Data;
666 * \brief sort the hash by your sort function. see the following sample.
667 * this will result in the sequence the hashing allgorithm produces it by default.
668 * \param Hash the list to sort
669 * \param SortBy Sortfunction; see below how to implement this
671 void SortByPayload(HashList *Hash, CompareFunc SortBy)
673 if (Hash->nMembersUsed < 2)
675 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
683 * given you've put char * into your hash as a payload, a sort function might
685 * int SortByChar(const void* First, const void* Second)
688 * a = (char*) GetSearchPayload(First);
689 * b = (char*) GetSearchPayload(Second);
690 * return strcmp (a, b);
696 * Generic function to free a pointer. This can be used as a callback with the
697 * hash table, even on systems where free() is defined as a macro or has had other
698 * horrible things done to it.
700 void generic_free_handler(void *ptr) {