retry on network failure during url fetch
[ppastats.git] / src / cache.c
1 /*
2     Copyright (C) 2011 jeanfi@gmail.com
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17     02110-1301 USA
18 */
19
20 #include <string.h>
21
22 #include "cache.h"
23 #include "ppastats.h"
24
25 #include <stdlib.h>
26 #include <stdio.h>
27
28 /*
29   Simple cache implementation but should be enough for storing LP data.
30 */
31
32 struct entry {
33         const char *key;
34         const void *value;
35         void (*fct_cleanup)(void *);
36 };
37
38 #define CAPACITY 1024
39
40 struct cache {
41         int size;
42         struct entry entries[CAPACITY];
43 };
44
45 static struct cache cache;
46
47 const void *cache_get(const char *key)
48 {
49         int i;
50
51         for (i = 0; i < cache.size; i++)
52                 if (!strcmp(cache.entries[i].key, key)) {
53                         if (debug)
54                                 printf("DEBUG: cache hit %s\n", key);
55
56                         return cache.entries[i].value;
57                 }
58
59         if (debug)
60                 printf("DEBUG: cache miss %s\n", key);
61
62         return NULL;
63 }
64
65 void cache_put(const char *key, const void *value,
66                void (*fct_cleanup)(void *))
67 {
68         if (cache.size == CAPACITY) {
69                 fprintf(stderr, "WARNING: exceed cache capacity\n");
70                 return ;
71         }
72
73         cache.entries[cache.size].key = strdup(key);
74         cache.entries[cache.size].value = value;
75         cache.entries[cache.size].fct_cleanup = fct_cleanup;
76
77         cache.size++;
78 }
79
80 void cache_cleanup()
81 {
82         int i;
83
84         for (i = 0; i < cache.size; i++) {
85                 free((char *)cache.entries[i].key);
86                 cache.entries[i].fct_cleanup((void *)cache.entries[i].value);
87         }
88 }