1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #ifdef ASSERT_DEBUG
5 #include <assert.h>
6 #endif
7 #include "conf.h"
8 #include "uthash.h"
9 #include "cache.h"
10
11 /*
12 Hash table
13 */
14
15 typedef struct __item_ {
16 char *key;
17 void *ptr;
18 UT_hash_handle hh;
19 } item_t;
20
21 item_t *cache = NULL;
22
23 /*
24 Configure caching system
25 */
26
cache_init(config_t * config)27 int cache_init(config_t *config)
28 {
29 cache = NULL;
30 return 1;
31 }
32
33 /*
34 Add an item to the cache
35 */
36
cache_add(const char * key,const void * ptr)37 int cache_add(const char *key, const void *ptr)
38 {
39 char *p = NULL;
40 item_t *i = NULL;
41
42 #ifdef ASSERT_DEBUG
43 assert(key != NULL);
44 assert(ptr != NULL);
45 #endif
46
47 i = malloc(sizeof(item_t));
48 if (i == NULL) {
49 fprintf(stderr, "cache_add: malloc failed\n");
50 return 0;
51 }
52
53 memset(i, 0, sizeof(item_t));
54
55 i->key = strdup(key);
56 if (i->key == NULL) {
57 fprintf(stderr, "cache_add: strdup failed\n");
58 return 0;
59 }
60
61 for (p = i->key; *p; p++) {
62 if ((*p >= 'A') && (*p <= 'Z'))
63 *p = tolower(*p);
64 }
65
66 i->ptr = (void *)ptr;
67
68 HASH_ADD_KEYPTR(hh, cache, i->key, strlen(i->key), i);
69
70 #ifdef CACHE_DEBUG
71 printf("cache: Added %p as %s\n", ptr, key);
72 #endif
73
74 return 1;
75 }
76
77 /*
78 Lookup a cached item
79 */
80
cache_lookup(const char * key)81 void *cache_lookup(const char *key)
82 {
83 item_t *i = NULL;
84
85 #ifdef ASSERT_DEBUG
86 assert(key != NULL);
87 #endif
88
89 HASH_FIND(hh, cache, key, strlen(key), i);
90
91 #ifdef CACHE_DEBUG
92 if (i)
93 printf("cache: Found %p at %s\n", i->ptr, key);
94 else
95 printf("cache: Not found: %s\n", key);
96 #endif
97
98 if (i)
99 return i->ptr;
100
101 return NULL;
102 }
103
104 /*
105 Remove a cached item
106 */
107
cache_remove(const char * key)108 void cache_remove(const char *key)
109 {
110 item_t *i = NULL;
111
112 #ifdef ASSERT_DEBUG
113 assert(key != NULL);
114 #endif
115
116 HASH_FIND(hh, cache, key, strlen(key), i);
117
118 if (i) {
119 #ifdef CACHE_DEBUG
120 printf("cache: Deleting %p at %s\n", i->ptr, key);
121 #endif
122 HASH_DEL(cache, i);
123 }
124
125 #ifdef CACHE_DEBUG
126 else
127 printf("cache: Nothing to delete at %s\n", key);
128 #endif
129 }
130