Merged revisions 10129-10142 via svnmerge from
[wvapps.git] / funfs / wvdiskcache.cc
blobc20c554d9666ca2f9d20548724603ad23fa58e2d
1 #include <wvdiskcache.h>
3 #ifdef WITH_GDBM
5 #define BYTESTOKB(x) (x + ((1 << 10) - 1)) >> 10
7 WvDiskCache::WvDiskCache(WvStringParm hashpath, int megabytes)
8 : backend(hashpath)
10 cur_size = 0;
11 set_max(megabytes);
12 head = tail = "";
13 xcount = 0;
16 void WvDiskCache::add(WvStringParm path, size_t size)
18 xcount++;
20 backend.add(path, DCFileInfo(size, head, ""), true);
22 if (!!head)
24 DCFileInfo fi = backend.find(head);
25 fi.prev = path;
26 backend.add(head, fi, true);
27 head = path;
29 else
31 head = path;
33 if (!tail)
35 tail = path;
38 cur_size += BYTESTOKB(size);
39 purge();
42 void WvDiskCache::remove(WvString path)
44 xcount--;
46 DCFileInfo fi = backend.find(path);
47 backend.remove(path);
49 cur_size -= BYTESTOKB(fi.size);
51 if (path == head || path == tail)
53 if (path == head)
55 head = xcount ? fi.next : WvString("");
57 if (path == tail)
59 tail = xcount ? fi.prev : WvString("");
62 else
64 DCFileInfo pfi = backend.find(fi.prev);
65 pfi.prev = fi.prev;
66 backend.add(fi.prev, pfi, true);
68 DCFileInfo nfi = backend.find(fi.prev);
69 nfi.next = fi.next;
70 backend.add(fi.next, nfi, true);
73 if (callback)
74 callback(path);
77 void WvDiskCache::purge()
79 while (cur_size > max_size)
81 remove(tail);
85 void WvDiskCache::set_max(int megabytes)
87 max_size = megabytes * 1024;
88 purge();
91 #endif