Debian Codegraph @

crt/aws-c-common/source/fifo_cache.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include <aws/common/fifo_cache.h>
6
7 static int s_fifo_cache_put(struct aws_cache *cache, const void *key, void *p_value);
8
9 static struct aws_cache_vtable s_fifo_cache_vtable = {
10 .destroy = aws_cache_base_default_destroy,
11 .find = aws_cache_base_default_find,
12 .put = s_fifo_cache_put,
13 .remove = aws_cache_base_default_remove,
14 .clear = aws_cache_base_default_clear,
15 .get_element_count = aws_cache_base_default_get_element_count,
16 };
17
18 struct aws_cache *aws_cache_new_fifo(
19 struct aws_allocator *allocator,
20 aws_hash_fn *hash_fn,
21 aws_hash_callback_eq_fn *equals_fn,
22 aws_hash_callback_destroy_fn *destroy_key_fn,
23 aws_hash_callback_destroy_fn *destroy_value_fn,
24 size_t max_items) {
25 AWS_ASSERT(allocator);
26 AWS_ASSERT(max_items);
27
28 struct aws_cache *fifo_cache = aws_mem_calloc(allocator, 1, sizeof(struct aws_cache));
29 if (!fifo_cache) {
30 return NULL;
31 }
32 fifo_cache->allocator = allocator;
33 fifo_cache->max_items = max_items;
34 fifo_cache->vtable = &s_fifo_cache_vtable;
35 if (aws_linked_hash_table_init(
36 &fifo_cache->table, allocator, hash_fn, equals_fn, destroy_key_fn, destroy_value_fn, max_items)) {
37 return NULL;
38 }
39 return fifo_cache;
40 }
41
42 /* fifo cache put implementation */
43 static int s_fifo_cache_put(struct aws_cache *cache, const void *key, void *p_value) {
44 if (aws_linked_hash_table_put(&cache->table, key, p_value)) {
45 return AWS_OP_ERR;
46 }
47
48 /* Manage the space if we actually added a new element and the cache is full. */
49 if (aws_linked_hash_table_get_element_count(&cache->table) > cache->max_items) {
50 /* we're over the cache size limit. Remove whatever is in the front of
51 * the linked_hash_table, which is the oldest element */
52 const struct aws_linked_list *list = aws_linked_hash_table_get_iteration_list(&cache->table);
53 struct aws_linked_list_node *node = aws_linked_list_front(list);
54 struct aws_linked_hash_table_node *table_node = AWS_CONTAINER_OF(node, struct aws_linked_hash_table_node, node);
55 return aws_linked_hash_table_remove(&cache->table, table_node->key);
56 }
57
58 return AWS_OP_SUCCESS;
59 }