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)
67 for (i=0; i < Hash->nMembersUsed; i++) {
72 if (Hash->LookupTable[i - 1] == NULL)
75 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
77 if (Hash->LookupTable[i] == NULL) {
82 Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
83 KeyStr = Hash->LookupTable[i]->HashKey;
86 Trans(Previous, Next, i % 2);
87 PrintEntry(KeyStr, Next, i % 2);
94 * \brief verify the contents of a hash list; here for debugging purposes.
95 * \param Hash your Hashlist structure
96 * \param First Functionpointer to allow you to print your payload
97 * \param Second Functionpointer to allow you to print your payload
100 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
104 const char *bla = "";
107 if (Hash->MyKeys != NULL)
110 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
112 printf("----------------------------------\n");
114 for (i=0; i < Hash->nMembersUsed; i++) {
116 if (Hash->LookupTable[i] == NULL)
124 key = Hash->LookupTable[i]->Key;
125 foo = Hash->LookupTable[i]->HashKey;
127 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
129 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
132 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
136 printf("----------------------------------\n");
143 * \brief instanciate a new hashlist
144 * \returns the newly allocated list.
146 HashList *NewHash(int Uniq, HashFunc F)
149 NewList = malloc (sizeof(HashList));
150 memset(NewList, 0, sizeof(HashList));
152 NewList->Members = malloc(sizeof(Payload*) * 100);
153 memset(NewList->Members, 0, sizeof(Payload*) * 100);
155 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
156 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
158 NewList->MemberSize = 100;
159 NewList->tainted = 0;
160 NewList->uniq = Uniq;
161 NewList->Algorithm = F;
166 int GetCount(HashList *Hash)
168 return Hash->nMembersUsed;
173 * \brief private destructor for one hash element.
174 * \param Data an element to free using the user provided destructor, or just plain free
176 static void DeleteHashPayload (Payload *Data)
178 /** do we have a destructor for our payload? */
179 if (Data->Destructor)
180 Data->Destructor(Data->Data);
186 * \brief destroy a hashlist and all of its members
187 * \param Hash Hash to destroy. Is NULL'ed so you are shure its done.
189 void DeleteHash(HashList **Hash)
197 for (i=0; i < FreeMe->nMembersUsed; i++)
199 /** get rid of our payload */
200 if (FreeMe->Members[i] != NULL)
202 DeleteHashPayload(FreeMe->Members[i]);
203 free(FreeMe->Members[i]);
205 /** delete our hashing data */
206 if (FreeMe->LookupTable[i] != NULL)
208 free(FreeMe->LookupTable[i]->HashKey);
209 free(FreeMe->LookupTable[i]);
212 /** now, free our arrays... */
213 free(FreeMe->LookupTable);
214 free(FreeMe->Members);
215 /** did s.b. want an array of our keys? free them. */
216 if (FreeMe->MyKeys != NULL)
217 free(FreeMe->MyKeys);
218 /** buye bye cruel world. */
224 * \brief Private function to increase the hash size.
225 * \param Hash the Hasharray to increase
227 static void IncreaseHashSize(HashList *Hash)
229 /* Ok, Our space is used up. Double the available space. */
230 Payload **NewPayloadArea;
233 /** double our payload area */
234 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
235 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
236 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
238 Hash->Members = NewPayloadArea;
240 /** double our hashtable area */
241 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
242 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
243 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
244 free(Hash->LookupTable);
245 Hash->LookupTable = NewTable;
247 Hash->MemberSize *= 2;
252 * \brief private function to add a new item to / replace an existing in - the hashlist
253 * if the hash list is full, its re-alloced with double size.
254 * \parame Hash our hashlist to manipulate
255 * \param HashPos where should we insert / replace?
256 * \param HashKeyStr the Hash-String
257 * \param HKLen length of HashKeyStr
258 * \param Data your Payload to add
259 * \param Destructor Functionpointer to free Data. if NULL, default free() is used.
261 static void InsertHashItem(HashList *Hash,
264 const char *HashKeyStr,
267 DeleteHashDataFunc Destructor)
269 Payload *NewPayloadItem;
272 if (Hash->nMembersUsed >= Hash->MemberSize)
273 IncreaseHashSize (Hash);
275 /** Arrange the payload */
276 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
277 NewPayloadItem->Data = Data;
278 NewPayloadItem->Destructor = Destructor;
279 /** Arrange the hashkey */
280 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
281 NewHashKey->HashKey = (char *) malloc (HKLen + 1);
282 NewHashKey->HKLen = HKLen;
283 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
284 NewHashKey->Key = HashBinKey;
285 NewHashKey->PL = NewPayloadItem;
286 /** our payload is queued at the end... */
287 NewHashKey->Position = Hash->nMembersUsed;
288 /** but if we should be sorted into a specific place... */
289 if ((Hash->nMembersUsed != 0) &&
290 (HashPos != Hash->nMembersUsed) ) {
293 ItemsAfter = Hash->nMembersUsed - HashPos;
294 /** make space were we can fill us in */
297 memmove(&Hash->LookupTable[HashPos + 1],
298 &Hash->LookupTable[HashPos],
299 ItemsAfter * sizeof(HashKey*));
303 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
304 Hash->LookupTable[HashPos] = NewHashKey;
305 Hash->nMembersUsed++;
309 * \brief if the user has tainted the hash, but wants to insert / search items by their key
310 * we need to search linear through the array. You have been warned that this will take more time!
311 * \param Hash Our Hash to manipulate
312 * \param HashBinKey the Hash-Number to lookup.
313 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
315 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
319 for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
320 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
328 * \brief Private function to lookup the Item / the closest position to put it in
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 FindInHash(HashList *Hash, long HashBinKey)
339 return FindInTaintedHash(Hash, HashBinKey);
341 SearchPos = Hash->nMembersUsed / 2;
342 StepWidth = SearchPos / 2;
343 while ((SearchPos > 0) &&
344 (SearchPos < Hash->nMembersUsed))
346 /** Did we find it? */
347 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
350 /** are we Aproximating in big steps? */
352 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
353 SearchPos -= StepWidth;
355 SearchPos += StepWidth;
358 else { /** We are right next to our target, within 4 positions */
359 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
360 if ((SearchPos > 0) &&
361 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
366 if ((SearchPos + 1 < Hash->nMembersUsed) &&
367 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
378 * \brief private abstract wrapper around the hashing algorithm
379 * \param HKey the hash string
380 * \param HKLen length of HKey
381 * \returns the calculated hash value
383 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
385 if (Hash->Algorithm == NULL)
386 return hashlittle(HKey, HKLen, 9283457);
388 return Hash->Algorithm(HKey, HKLen);
393 * \brief Add a new / Replace an existing item in the Hash
394 * \param HashList the list to manipulate
395 * \param HKey the hash-string to store Data under
396 * \param HKeyLen Length of HKey
397 * \param Data the payload you want to associate with HKey
398 * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
400 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
405 /** first, find out were we could fit in... */
406 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
407 HashAt = FindInHash(Hash, HashBinKey);
409 if (HashAt >= Hash->MemberSize)
410 IncreaseHashSize (Hash);
412 /** oh, we're brand new... */
413 if (Hash->LookupTable[HashAt] == NULL) {
414 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
415 }/** Insert After? */
416 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
417 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
418 }/** Insert before? */
419 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
420 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
422 else { /** Ok, we have a colision. replace it. */
426 PayloadPos = Hash->LookupTable[HashAt]->Position;
427 DeleteHashPayload(Hash->Members[PayloadPos]);
428 Hash->Members[PayloadPos]->Data = Data;
429 Hash->Members[PayloadPos]->Destructor = DeleteIt;
432 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
438 * \brief Lookup the Data associated with HKey
439 * \param Hash the Hashlist to search in
440 * \param HKey the hashkey to look up
441 * \param HKLen length of HKey
442 * \param Data returns the Data associated with HKey
443 * \returns 0 if not found, 1 if.
445 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
454 /** first, find out were we could be... */
455 HashBinKey = CalcHashKey(Hash, HKey, HKLen);
456 HashAt = FindInHash(Hash, HashBinKey);
457 if ((HashAt < 0) || /**< Not found at the lower edge? */
458 (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
459 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
463 else { /** GOTCHA! */
466 MemberPosition = Hash->LookupTable[HashAt]->Position;
467 *Data = Hash->Members[MemberPosition]->Data;
473 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
479 * \brief get the Keys present in this hash, simila to array_keys() in PHP
480 * Attention: List remains to Hash! don't modify or free it!
481 * \param Hash Your Hashlist to extract the keys from
482 * \param List returns the list of hashkeys stored in Hash
484 int GetHashKeys(HashList *Hash, char ***List)
487 if (Hash->MyKeys != NULL)
490 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
491 for (i=0; i < Hash->nMembersUsed; i++) {
493 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
495 *List = (char**)Hash->MyKeys;
496 return Hash->nMembersUsed;
500 * \brief creates a hash-linear iterator object
501 * \returns the hash iterator
503 HashPos *GetNewHashPos(void)
507 Ret = (HashPos*)malloc(sizeof(HashPos));
513 * \brief frees a linear hash iterator
515 void DeleteHashPos(HashPos **DelMe)
523 * \brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
524 * \param Hash your Hashlist to follow
525 * \param HKLen returns Length of Hashkey Returned
526 * \param HashKey returns the Hashkey corrosponding to HashPos
527 * \param Data returns the Data found at HashPos
528 * \returns whether the item was found or not.
530 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, char **HashKey, void **Data)
534 if (Hash->nMembersUsed <= At->Position)
536 *HKLen = Hash->LookupTable[At->Position]->HKLen;
537 *HashKey = Hash->LookupTable[At->Position]->HashKey;
538 PayloadPos = Hash->LookupTable[At->Position]->Position;
539 *Data = Hash->Members[PayloadPos]->Data;
545 * \brief sorting function for sorting the Hash alphabeticaly by their strings
546 * \param Key1 first item
547 * \param Key2 second item
549 static int SortByKeys(const void *Key1, const void* Key2)
551 HashKey *HKey1, *HKey2;
552 HKey1 = *(HashKey**) Key1;
553 HKey2 = *(HashKey**) Key2;
555 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
559 * \brief sorting function for sorting the Hash alphabeticaly reverse by their strings
560 * \param Key1 first item
561 * \param Key2 second item
563 static int SortByKeysRev(const void *Key1, const void* Key2)
565 HashKey *HKey1, *HKey2;
566 HKey1 = *(HashKey**) Key1;
567 HKey2 = *(HashKey**) Key2;
569 return strcasecmp(HKey2->HashKey, HKey1->HashKey);
573 * \brief sorting function to regain hash-sequence and revert tainted status
574 * \param Key1 first item
575 * \param Key2 second item
577 static int SortByHashKeys(const void *Key1, const void* Key2)
579 HashKey *HKey1, *HKey2;
580 HKey1 = *(HashKey**) Key1;
581 HKey2 = *(HashKey**) Key2;
583 return HKey1->Key > HKey2->Key;
588 * \brief sort the hash alphabeticaly by their keys.
589 * Caution: This taints the hashlist, so accessing it later
590 * will be significantly slower! You can un-taint it by SortByHashKeyStr
591 * \param Hash the list to sort
592 * \param Order 0/1 Forward/Backward
594 void SortByHashKey(HashList *Hash, int Order)
596 if (Hash->nMembersUsed < 2)
598 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*),
599 (Order)?SortByKeys:SortByKeysRev);
604 * \brief sort the hash by their keys (so it regains untainted state).
605 * this will result in the sequence the hashing allgorithm produces it by default.
606 * \param Hash the list to sort
608 void SortByHashKeyStr(HashList *Hash)
611 if (Hash->nMembersUsed < 2)
613 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
618 * \brief gives user sort routines access to the hash payload
619 * \param Searchentry to retrieve Data to
620 * \returns Data belonging to HashVoid
622 const void *GetSearchPayload(const void *HashVoid)
624 return (*(HashKey**)HashVoid)->PL->Data;
628 * \brief sort the hash by your sort function. see the following sample.
629 * this will result in the sequence the hashing allgorithm produces it by default.
630 * \param Hash the list to sort
631 * \param SortBy Sortfunction; see below how to implement this
633 void SortByPayload(HashList *Hash, CompareFunc SortBy)
635 if (Hash->nMembersUsed < 2)
637 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
645 * given you've put char * into your hash as a payload, a sort function might
647 * int SortByChar(const void* First, const void* Second)
650 * a = (char*) GetSearchPayload(First);
651 * b = (char*) GetSearchPayload(Second);
652 * return strcmp (a, b);