1 /*-------------------------------------------------------------------------------
2 
3 	BARONY
4 	File: hash.cpp
5 	Desc: module for generating hash values and working with tables
6 
7 	Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
8 	See LICENSE for details.
9 
10 -------------------------------------------------------------------------------*/
11 
12 #include "main.hpp"
13 #include "hash.hpp"
14 
djb2Hash(char * str)15 unsigned long djb2Hash(char* str)
16 {
17 	unsigned long hash = 5381;
18 	int c;
19 
20 	while (c = *str++)
21 	{
22 		hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
23 	}
24 
25 	return hash;
26 }
27 
ttfTextHash_deconstructor(void * data)28 void ttfTextHash_deconstructor(void* data)
29 {
30 	ttfTextHash_t* hashedVal = static_cast<ttfTextHash_t*>(data);
31 	SDL_FreeSurface(hashedVal->surf);
32 	free(hashedVal->str);
33 	free(data);
34 }
35 
ttfTextHashRetrieve(list_t * buckets,char * str,TTF_Font * font,bool outline)36 SDL_Surface* ttfTextHashRetrieve(list_t* buckets, char* str, TTF_Font* font, bool outline)
37 {
38 	node_t* node;
39 
40 	// retrieve bucket
41 	list_t* list = &buckets[djb2Hash(str) % HASH_SIZE];
42 
43 	// find data in bucket (linear search)
44 	for ( node = list->first; node != NULL; node = node->next )
45 	{
46 		ttfTextHash_t* hashedVal = (ttfTextHash_t*)node->element;
47 		if ( !strcmp(hashedVal->str, str) && hashedVal->font == font && hashedVal->outline == outline )
48 		{
49 			return hashedVal->surf;
50 		}
51 	}
52 
53 	return NULL;
54 }
55 
ttfTextHashStore(list_t * buckets,char * str,TTF_Font * font,bool outline,SDL_Surface * surf)56 SDL_Surface* ttfTextHashStore(list_t* buckets, char* str, TTF_Font* font, bool outline, SDL_Surface* surf)
57 {
58 	ttfTextHash_t* hashedVal;
59 	node_t* node;
60 
61 	// retrieve bucket
62 	list_t* list = &buckets[djb2Hash(str) % HASH_SIZE];
63 
64 	// add surface to bucket
65 	if ( (node = list_AddNodeFirst(list)) == NULL )
66 	{
67 		return NULL;
68 	}
69 	else
70 	{
71 		hashedVal = (ttfTextHash_t*) malloc(sizeof(ttfTextHash_t));
72 		hashedVal->str = (char*) calloc(strlen(str) + 1, sizeof(char));
73 		strcpy(hashedVal->str, str);
74 		hashedVal->surf = surf;
75 		hashedVal->font = font;
76 		hashedVal->outline = outline;
77 
78 		node->deconstructor = &ttfTextHash_deconstructor;
79 		node->size = sizeof(ttfTextHash_t);
80 		node->element = hashedVal;
81 
82 		return surf;
83 	}
84 }