| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#include <aws/common/lifo_cache.h> |
| 6 |
static int s_lifo_cache_put(struct aws_cache *cache, const void *key, void *p_value); |
| 7 |
|
| 8 |
static struct aws_cache_vtable s_lifo_cache_vtable = { |
| 9 |
.destroy = aws_cache_base_default_destroy, |
| 10 |
.find = aws_cache_base_default_find, |
| 11 |
.put = s_lifo_cache_put, |
| 12 |
.remove = aws_cache_base_default_remove, |
| 13 |
.clear = aws_cache_base_default_clear, |
| 14 |
.get_element_count = aws_cache_base_default_get_element_count, |
| 15 |
}; |
| 16 |
|
| 17 |
struct aws_cache *aws_cache_new_lifo( |
| 18 |
struct aws_allocator *allocator, |
| 19 |
aws_hash_fn *hash_fn, |
| 20 |
aws_hash_callback_eq_fn *equals_fn, |
| 21 |
aws_hash_callback_destroy_fn *destroy_key_fn, |
| 22 |
aws_hash_callback_destroy_fn *destroy_value_fn, |
| 23 |
size_t max_items) { |
| 24 |
AWS_ASSERT(allocator); |
| 25 |
AWS_ASSERT(max_items); |
| 26 |
|
| 27 |
struct aws_cache *lifo_cache = aws_mem_calloc(allocator, 1, sizeof(struct aws_cache)); |
| 28 |
if (!lifo_cache) { |
| 29 |
return NULL; |
| 30 |
} |
| 31 |
lifo_cache->allocator = allocator; |
| 32 |
lifo_cache->max_items = max_items; |
| 33 |
lifo_cache->vtable = &s_lifo_cache_vtable; |
| 34 |
if (aws_linked_hash_table_init( |
| 35 |
&lifo_cache->table, allocator, hash_fn, equals_fn, destroy_key_fn, destroy_value_fn, max_items)) { |
| 36 |
return NULL; |
| 37 |
} |
| 38 |
return lifo_cache; |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
static int s_lifo_cache_put(struct aws_cache *cache, const void *key, void *p_value) { |
| 43 |
if (aws_linked_hash_table_put(&cache->table, key, p_value)) { |
| 44 |
return AWS_OP_ERR; |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
if (aws_linked_hash_table_get_element_count(&cache->table) > cache->max_items) { |
| 49 |
|
| 50 |
|
| 51 |
const struct aws_linked_list *list = aws_linked_hash_table_get_iteration_list(&cache->table); |
| 52 |
struct aws_linked_list_node *node = aws_linked_list_back(list); |
| 53 |
if (!node->prev) { |
| 54 |
return AWS_OP_SUCCESS; |
| 55 |
} |
| 56 |
struct aws_linked_hash_table_node *table_node = |
| 57 |
AWS_CONTAINER_OF(node->prev, struct aws_linked_hash_table_node, node); |
| 58 |
return aws_linked_hash_table_remove(&cache->table, table_node->key); |
| 59 |
} |
| 60 |
|
| 61 |
return AWS_OP_SUCCESS; |
| 62 |
} |