1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
3 * Copyright (C) 2000-2012 Jeffrey Stedfast
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public License
7 * as published by the Free Software Foundation; either version 2.1
8 * of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free
17 * Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
30 cache_node_free (gpointer node_data)
32 CacheNode *node = (CacheNode *) node_data;
33 Cache *cache = node->cache;
35 cache->free_node (node);
38 g_slice_free1 (cache->node_size, node);
43 cache_new (CacheNodeExpireFunc expire, CacheNodeFreeFunc free_node, size_t node_size, size_t max_size)
47 cache = g_new (Cache, 1);
48 list_init (&cache->list);
49 cache->expire = expire;
50 cache->free_node = free_node;
51 cache->node_hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, cache_node_free);
52 cache->node_size = node_size;
53 cache->max_size = max_size;
61 cache_free (Cache *cache)
63 g_hash_table_destroy (cache->node_hash);
69 cache_expire_unused (Cache *cache)
71 ListNode *node, *prev;
73 node = cache->list.tailpred;
74 while (node->prev && cache->size > cache->max_size) {
76 if (cache->expire (cache, (CacheNode *) node)) {
78 g_hash_table_remove (cache->node_hash, ((CacheNode *) node)->key);
86 cache_node_insert (Cache *cache, const char *key)
92 if (cache->size > cache->max_size)
93 cache_expire_unused (cache);
95 node = g_slice_alloc (cache->node_size);
96 node->key = g_strdup (key);
99 g_hash_table_insert (cache->node_hash, node->key, node);
100 list_prepend (&cache->list, (ListNode *) node);
106 cache_node_lookup (Cache *cache, const char *key, gboolean use)
110 node = g_hash_table_lookup (cache->node_hash, key);
112 list_unlink ((ListNode *) node);
113 list_prepend (&cache->list, (ListNode *) node);
120 cache_node_expire (CacheNode *node)
125 list_unlink ((ListNode *) node);
126 g_hash_table_remove (cache->node_hash, node->key);