fifo_cache.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. static int s_fifo_cache_put(struct aws_cache *cache, const void *key, void *p_value);
  7. static struct aws_cache_vtable s_fifo_cache_vtable = {
  8. .destroy = aws_cache_base_default_destroy,
  9. .find = aws_cache_base_default_find,
  10. .put = s_fifo_cache_put,
  11. .remove = aws_cache_base_default_remove,
  12. .clear = aws_cache_base_default_clear,
  13. .get_element_count = aws_cache_base_default_get_element_count,
  14. };
  15. struct aws_cache *aws_cache_new_fifo(
  16. struct aws_allocator *allocator,
  17. aws_hash_fn *hash_fn,
  18. aws_hash_callback_eq_fn *equals_fn,
  19. aws_hash_callback_destroy_fn *destroy_key_fn,
  20. aws_hash_callback_destroy_fn *destroy_value_fn,
  21. size_t max_items) {
  22. AWS_ASSERT(allocator);
  23. AWS_ASSERT(max_items);
  24. struct aws_cache *fifo_cache = aws_mem_calloc(allocator, 1, sizeof(struct aws_cache));
  25. if (!fifo_cache) {
  26. return NULL;
  27. }
  28. fifo_cache->allocator = allocator;
  29. fifo_cache->max_items = max_items;
  30. fifo_cache->vtable = &s_fifo_cache_vtable;
  31. if (aws_linked_hash_table_init(
  32. &fifo_cache->table, allocator, hash_fn, equals_fn, destroy_key_fn, destroy_value_fn, max_items)) {
  33. return NULL;
  34. }
  35. return fifo_cache;
  36. }
  37. /* fifo cache put implementation */
  38. static int s_fifo_cache_put(struct aws_cache *cache, const void *key, void *p_value) {
  39. if (aws_linked_hash_table_put(&cache->table, key, p_value)) {
  40. return AWS_OP_ERR;
  41. }
  42. /* Manage the space if we actually added a new element and the cache is full. */
  43. if (aws_linked_hash_table_get_element_count(&cache->table) > cache->max_items) {
  44. /* we're over the cache size limit. Remove whatever is in the front of
  45. * the linked_hash_table, which is the oldest element */
  46. const struct aws_linked_list *list = aws_linked_hash_table_get_iteration_list(&cache->table);
  47. struct aws_linked_list_node *node = aws_linked_list_front(list);
  48. struct aws_linked_hash_table_node *table_node = AWS_CONTAINER_OF(node, struct aws_linked_hash_table_node, node);
  49. return aws_linked_hash_table_remove(&cache->table, table_node->key);
  50. }
  51. return AWS_OP_SUCCESS;
  52. }