cache.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include "cache.h"
  2. cache_page_t* cache_page_new(cache_t* parent, db_data_t* data)
  3. {
  4. cache_page_t* cp = NULL;
  5. cp = (cache_page_t*) malloc(sizeof(cache_page_t));
  6. if(!cp)
  7. {
  8. fprintf(stderr, "Unable to allocate %ld bytes for cache page (cache_page_new())",
  9. sizeof(cache_page_t));
  10. perror(" ");
  11. return NULL;
  12. }
  13. memset(cp, 0, sizeof(cache_page_t));
  14. cp->ptr=data;
  15. cp->page_size=parent->page_size;
  16. return cp;
  17. }
  18. void cache_page_set_value(cache_page_t* cp, db_interval_t inter, db_data_t* data)
  19. {
  20. memcpy(cp->ptr, data, sizeof(db_data_t)*cp->page_size);
  21. cp->inter=inter;
  22. }
  23. void cache_page_insert(cache_page_t* parent, cache_page_t* new)
  24. {
  25. cache_page_t *tmp = parent->next;
  26. parent->next=new;
  27. new->next=tmp;
  28. new->prev=parent;
  29. if(tmp) tmp->prev=new;
  30. }
  31. cache_page_t* cache_page_remove(cache_page_t* tr)
  32. {
  33. if(tr->next)
  34. tr->next->prev=tr->prev;
  35. if(tr->prev)
  36. tr->prev->next=tr->next;
  37. tr->next=NULL;
  38. tr->prev=NULL;
  39. return tr;
  40. }
  41. void cache_page_free(cache_page_t* tr)
  42. {
  43. free(tr);
  44. }
  45. int cache_init(cache_t *cache, int page_size_byte, int page_count)
  46. {
  47. cache_page_t *curr=NULL;
  48. int i;
  49. if(!cache) return -1;
  50. cache->page_count=page_count;
  51. cache->page_size=(1+page_size_byte)/sizeof(db_data_t*);
  52. cache->cache=(db_data_t*) malloc((page_count)*page_size_byte);
  53. if(!cache->cache)
  54. {
  55. fprintf(stderr, "Unable to allocate %d bytes for cache (cache_init())",
  56. (page_count)*page_size_byte);
  57. perror(" ");
  58. return -1;
  59. }
  60. cache->head=cache_page_new(cache, NULL);
  61. for(i=0, curr=cache->head; i<page_count; i++, curr=curr->next)
  62. {
  63. cache_page_t *cp = cache_page_new(cache, &cache->cache[i]);
  64. cache_page_insert(curr, cp);
  65. }
  66. return 0;
  67. }
  68. void cache_free(cache_t *cache)
  69. {
  70. cache_page_t* curr = cache->head;
  71. free(cache->cache);
  72. while(curr)
  73. {
  74. cache_page_t * c = curr;
  75. curr=curr->next;
  76. cache_page_free(c);
  77. }
  78. }
  79. void cache_get(cache_t* cache, db_time_t start, db_time_t end)
  80. {
  81. }
  82. void printcache(cache_page_t* cache)
  83. {
  84. cache_page_t *cp = cache->next;
  85. while(cp)
  86. {
  87. printf("%d ", cp->data);
  88. cp=cp->next;
  89. }
  90. printf("\n");
  91. }