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 Keye
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 long nMembersUsed; /**< how many pointers inside of the array are used? */
38 long MemberSize; /**< how big is Members and LookupTable? */
39 long tainted; /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
44 * \brief Anonymous Hash Iterator Object. used for traversing the whole array from outside
50 * \brief verify the contents of a hash list; here for debugging purposes.
51 * \param Hash your Hashlist structure
52 * \param First Functionpointer to allow you to print your payload
53 * \param Second Functionpointer to allow you to print your payload
56 int PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
63 if (Hash->MyKeys != NULL)
66 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
68 printf("----------------------------------\n");
70 for (i=0; i < Hash->nMembersUsed; i++) {
72 if (Hash->LookupTable[i] == NULL)
80 key = Hash->LookupTable[i]->Key;
81 foo = Hash->LookupTable[i]->HashKey;
83 bar = First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
85 bla = Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
88 printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
92 printf("----------------------------------\n");
99 * \brief instanciate a new hashlist
100 * \returns the newly allocated list.
102 HashList *NewHash(void)
105 NewList = malloc (sizeof(HashList));
106 memset(NewList, 0, sizeof(HashList));
108 NewList->Members = malloc(sizeof(Payload*) * 100);
109 memset(NewList->Members, 0, sizeof(Payload*) * 100);
111 NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
112 memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
114 NewList->MemberSize = 100;
115 NewList->tainted = 0;
121 * \brief private destructor for one hash element.
122 * \param Data an element to free using the user provided destructor, or just plain free
124 static void DeleteHashPayload (Payload *Data)
126 /** do we have a destructor for our payload? */
127 if (Data->Destructor)
128 Data->Destructor(Data->Data);
134 * \brief destroy a hashlist and all of its members
135 * \param Hash Hash to destroy. Is NULL'ed so you are shure its done.
137 void DeleteHash(HashList **Hash)
145 for (i=0; i < FreeMe->nMembersUsed; i++)
147 /** get rid of our payload */
148 if (FreeMe->Members[i] != NULL)
150 DeleteHashPayload(FreeMe->Members[i]);
151 free(FreeMe->Members[i]);
153 /** delete our hashing data */
154 if (FreeMe->LookupTable[i] != NULL)
156 free(FreeMe->LookupTable[i]->HashKey);
157 free(FreeMe->LookupTable[i]);
160 /** now, free our arrays... */
161 free(FreeMe->LookupTable);
162 free(FreeMe->Members);
163 /** did s.b. want an array of our keys? free them. */
164 if (FreeMe->MyKeys != NULL)
165 free(FreeMe->MyKeys);
166 /** buye bye cruel world. */
173 * \brief private function to add a new item to / replace an existing in - the hashlist
174 * if the hash list is full, its re-alloced with double size.
175 * \parame Hash our hashlist to manipulate
176 * \param HashPos where should we insert / replace?
177 * \param HashKeyStr the Hash-String
178 * \param HKLen length of HashKeyStr
179 * \param Data your Payload to add
180 * \param Destructor Functionpointer to free Data. if NULL, default free() is used.
182 static void InsertHashItem(HashList *Hash,
188 DeleteHashDataFunc Destructor)
190 Payload *NewPayloadItem;
193 if (Hash->nMembersUsed >= Hash->MemberSize)
195 /* Ok, Our space is used up. Double the available space. */
196 Payload **NewPayloadArea;
199 /** double our payload area */
200 NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
201 memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
202 memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
204 Hash->Members = NewPayloadArea;
206 /** double our hashtable area */
207 NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
208 memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
209 memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
210 free(Hash->LookupTable);
211 Hash->LookupTable = NewTable;
213 Hash->MemberSize *= 2;
215 /** Arrange the payload */
216 NewPayloadItem = (Payload*) malloc (sizeof(Payload));
217 NewPayloadItem->Data = Data;
218 NewPayloadItem->Destructor = Destructor;
219 /** Arrange the hashkey */
220 NewHashKey = (HashKey*) malloc (sizeof(HashKey));
221 NewHashKey->HashKey = (char *) malloc (HKLen + 1);
222 NewHashKey->HKLen = HKLen;
223 memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
224 NewHashKey->Key = HashBinKey;
225 NewHashKey->PL = NewPayloadItem;
226 /** our payload is queued at the end... */
227 NewHashKey->Position = Hash->nMembersUsed;
228 /** but if we should be sorted into a specific place... */
229 if ((Hash->nMembersUsed != 0) &&
230 (HashPos != Hash->nMembersUsed) ) {
234 ItemsAfter = Hash->nMembersUsed - HashPos;
236 /** make space were we can fill us in */
239 memmove(&Hash->LookupTable[InsertAt + 1],
240 &Hash->LookupTable[InsertAt],
241 ItemsAfter * sizeof(HashKey*));
245 Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
246 Hash->LookupTable[HashPos] = NewHashKey;
247 Hash->nMembersUsed++;
251 * \brief if the user has tainted the hash, but wants to insert / search items by their key
252 * we need to search linear through the array. You have been warned that this will take more time!
253 * \param Hash Our Hash to manipulate
254 * \param HashBinKey the Hash-Number to lookup.
255 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
257 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
261 for (SearchPos = 0; SearchPos < Hash->nMembersUsed; SearchPos ++) {
262 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
270 * \brief Private function to lookup the Item / the closest position to put it in
271 * \param Hash Our Hash to manipulate
272 * \param HashBinKey the Hash-Number to lookup.
273 * \returns the position (most closely) matching HashBinKey (-> Caller needs to compare! )
275 static long FindInHash(HashList *Hash, long HashBinKey)
281 return FindInTaintedHash(Hash, HashBinKey);
283 SearchPos = Hash->nMembersUsed / 2;
284 StepWidth = SearchPos / 2;
285 while ((SearchPos > 0) &&
286 (SearchPos < Hash->nMembersUsed))
288 /** Did we find it? */
289 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
292 /** are we Aproximating in big steps? */
294 if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
295 SearchPos -= StepWidth;
297 SearchPos += StepWidth;
300 else { /** We are right next to our target, within 4 positions */
301 if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
302 if ((SearchPos > 0) &&
303 (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
308 if ((SearchPos + 1 < Hash->nMembersUsed) &&
309 (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
320 * \brief private abstract wrapper around the hashing algorithm
321 * \param HKey the hash string
322 * \param HKLen length of HKey
323 * \returns the calculated hash value
325 inline static long CalcHashKey (char *HKey, long HKLen)
327 return hashlittle(HKey, HKLen, 9283457);
332 * \brief Add a new / Replace an existing item in the Hash
333 * \param HashList the list to manipulate
334 * \param HKey the hash-string to store Data under
335 * \param HKeyLen Length of HKey
336 * \param Data the payload you want to associate with HKey
337 * \param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
339 void Put(HashList *Hash, char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
344 /** first, find out were we could fit in... */
345 HashBinKey = CalcHashKey(HKey, HKLen);
346 HashAt = FindInHash(Hash, HashBinKey);
348 /** oh, we're brand new... */
349 if (Hash->LookupTable[HashAt] == NULL){
350 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
351 }/** Insert After? */
352 else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
353 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
354 }/** Insert before? */
355 else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
356 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
358 else { /** Ok, we have a colision. replace it. */
361 PayloadPos = Hash->LookupTable[HashAt]->Position;
362 DeleteHashPayload(Hash->Members[PayloadPos]);
363 Hash->Members[PayloadPos]->Data = Data;
364 Hash->Members[PayloadPos]->Destructor = DeleteIt;
369 * \brief Lookup the Data associated with HKey
370 * \param Hash the Hashlist to search in
371 * \param HKey the hashkey to look up
372 * \param HKLen length of HKey
373 * \param Data returns the Data associated with HKey
374 * \returns 0 if not found, 1 if.
376 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
385 /** first, find out were we could be... */
386 HashBinKey = CalcHashKey((char*)HKey, HKLen);
387 HashAt = FindInHash(Hash, HashBinKey);
388 if ((HashAt < 0) || /**< Not found at the lower edge? */
389 (HashAt >= Hash->nMembersUsed) || /**< Not found at the upper edge? */
390 (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
394 else { /** GOTCHA! */
397 MemberPosition = Hash->LookupTable[HashAt]->Position;
398 *Data = Hash->Members[MemberPosition]->Data;
404 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
410 * \brief get the Keys present in this hash, simila to array_keys() in PHP
411 * Attention: List remains to Hash! don't modify or free it!
412 * \param Hash Your Hashlist to extract the keys from
413 * \param List returns the list of hashkeys stored in Hash
415 int GetHashKeys(HashList *Hash, char ***List)
418 if (Hash->MyKeys != NULL)
421 Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nMembersUsed);
422 for (i=0; i < Hash->nMembersUsed; i++) {
424 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
426 *List = (char**)Hash->MyKeys;
427 return Hash->nMembersUsed;
431 * \brief creates a hash-linear iterator object
432 * \returns the hash iterator
434 HashPos *GetNewHashPos(void)
438 Ret = (HashPos*)malloc(sizeof(HashPos));
444 * \brief frees a linear hash iterator
446 void DeleteHashPos(HashPos **DelMe)
454 * \brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
455 * \param Hash your Hashlist to follow
456 * \param HKLen returns Length of Hashkey Returned
457 * \param HashKey returns the Hashkey corrosponding to HashPos
458 * \param Data returns the Data found at HashPos
459 * \returns whether the item was found or not.
461 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, char **HashKey, void **Data)
465 if (Hash->nMembersUsed <= At->Position)
467 *HKLen = Hash->LookupTable[At->Position]->HKLen;
468 *HashKey = Hash->LookupTable[At->Position]->HashKey;
469 PayloadPos = Hash->LookupTable[At->Position]->Position;
470 *Data = Hash->Members[PayloadPos]->Data;
476 * \brief sorting function for sorting the Hash alphabeticaly by their strings
477 * \param Key1 first item
478 * \param Key2 second item
480 static int SortByKeys(const void *Key1, const void* Key2)
482 HashKey *HKey1, *HKey2;
483 HKey1 = *(HashKey**) Key1;
484 HKey2 = *(HashKey**) Key2;
486 return strcasecmp(HKey1->HashKey, HKey2->HashKey);
490 * \brief sorting function to regain hash-sequence and revert tainted status
491 * \param Key1 first item
492 * \param Key2 second item
494 static int SortByHashKeys(const void *Key1, const void* Key2)
496 HashKey *HKey1, *HKey2;
497 HKey1 = *(HashKey**) Key1;
498 HKey2 = *(HashKey**) Key2;
500 return HKey1->Key > HKey2->Key;
505 * \brief sort the hash alphabeticaly by their keys.
506 * Caution: This taints the hashlist, so accessing it later
507 * will be significantly slower! You can un-taint it by SortByHashKeyStr
508 * \param Hash the list to sort
510 void SortByHashKey(HashList *Hash)
512 if (Hash->nMembersUsed < 2)
514 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByKeys);
519 * \brief sort the hash by their keys (so it regains untainted state).
520 * this will result in the sequence the hashing allgorithm produces it by default.
521 * \param Hash the list to sort
523 void SortByHashKeyStr(HashList *Hash)
526 if (Hash->nMembersUsed < 2)
528 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortByHashKeys);
533 * \brief gives user sort routines access to the hash payload
534 * \param Searchentry to retrieve Data to
535 * \returns Data belonging to HashVoid
537 const void *GetSearchPayload(const void *HashVoid)
539 return (*(HashKey**)HashVoid)->PL->Data;
543 * \brief sort the hash by your sort function. see the following sample.
544 * this will result in the sequence the hashing allgorithm produces it by default.
545 * \param Hash the list to sort
546 * \param SortBy Sortfunction; see below how to implement this
548 void SortByPayload(HashList *Hash, CompareFunc SortBy)
550 if (Hash->nMembersUsed < 2)
552 qsort(Hash->LookupTable, Hash->nMembersUsed, sizeof(HashKey*), SortBy);
560 * given you've put char * into your hash as a payload, a sort function might
562 * int SortByChar(const void* First, const void* Second)
565 * a = (char*) GetSearchPayload(First);
566 * b = (char*) GetSearchPayload(Second);
567 * return strcmp (a, b);