lifo_cache.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  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. static struct aws_cache_vtable s_lifo_cache_vtable = {
  8. .destroy = aws_cache_base_default_destroy,
  9. .find = aws_cache_base_default_find,
  10. .put = s_lifo_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_lifo(
  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 *lifo_cache = aws_mem_calloc(allocator, 1, sizeof(struct aws_cache));
  25. if (!lifo_cache) {
  26. return NULL;
  27. }
  28. lifo_cache->allocator = allocator;
  29. lifo_cache->max_items = max_items;
  30. lifo_cache->vtable = &s_lifo_cache_vtable;
  31. if (aws_linked_hash_table_init(
  32. &lifo_cache->table, allocator, hash_fn, equals_fn, destroy_key_fn, destroy_value_fn, max_items)) {
  33. return NULL;
  34. }
  35. return lifo_cache;
  36. }
  37. /* lifo cache put implementation */
  38. static int s_lifo_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 one before the back of the linked_hash_table,
  45. * which was the latest element before we put the new one */
  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_back(list);
  48. if (!node->prev) {
  49. return AWS_OP_SUCCESS;
  50. }
  51. struct aws_linked_hash_table_node *table_node =
  52. AWS_CONTAINER_OF(node->prev, struct aws_linked_hash_table_node, node);
  53. return aws_linked_hash_table_remove(&cache->table, table_node->key);
  54. }
  55. return AWS_OP_SUCCESS;
  56. }