implemented generic FileData cache
[geeqie.git] / src / filecache.c
1 /*
2  * Geeqie
3  * Copyright (C) 2008 The Geeqie Team
4  *
5  * Author: Vladimir Nadvornik
6  *
7  * This software is released under the GNU General Public License (GNU GPL).
8  * Please read the included file COPYING for more information.
9  * This software comes with no warranty of any kind, use at your own risk!
10  */
11
12
13 #include "main.h"
14 #include "filecache.h"
15
16 /* this implements a simple LRU algorithm */
17
18 struct _FileCacheData {
19         FileCacheReleaseFunc release;
20         GList *list;
21         gulong max_size;
22         gulong size;
23         };
24
25
26 FileCacheData *file_cache_new(FileCacheReleaseFunc release, gulong max_size)
27 {
28         FileCacheData *fc = g_new(FileCacheData, 1);
29         fc->release = release;
30         fc->list = NULL;
31         fc->max_size = max_size;
32         fc->size = 0;
33         return fc;
34 }
35
36 gint file_cache_get(FileCacheData *fc, FileData *fd)
37 {
38         GList *work;
39         if ((work = g_list_find(fc->list, fd)))
40                 {
41                 fc->list = g_list_remove_link(fc->list, work);
42                 fc->list = g_list_concat(work, fc->list);
43                 DEBUG_1("cache hit: %s", fd->path);
44                 return TRUE;
45                 }
46         DEBUG_1("cache miss: %s", fd->path);
47         return FALSE;
48 }
49
50 void file_cache_put(FileCacheData *fc, FileData *fd, gulong size)
51 {
52         GList *work;
53         FileData *last_fd;
54         if ((work = g_list_find(fc->list, fd)))
55                 { 
56                 /* entry already exists, move it to the beginning */
57                 fc->list = g_list_remove_link(fc->list, work);
58                 fc->list = g_list_concat(work, fc->list);
59                 return;
60                 }
61         
62         DEBUG_1("cache add: %s", fd->path);
63         file_data_ref(fd);
64         fc->list = g_list_prepend(fc->list, fd);
65         fc->size++; /* FIXME: use size */
66         
67         if (fc->size < fc->max_size) return;
68         
69         fc->size--;
70         work = g_list_last(fc->list);
71         last_fd = work->data;
72         fc->list = g_list_delete_link(fc->list, work);
73         DEBUG_1("cache remove: %s", last_fd->path);
74         fc->release(last_fd);
75         file_data_unref(last_fd);
76 }