![]() |
fuse_kafka
|
00001 00006 #ifndef TIME_QUEUE_C 00007 #define TIME_QUEUE_C 00008 #include <stdlib.h> 00009 #include <stdio.h> 00010 #include "time_queue.h" 00021 unsigned long time_queue_hash(unsigned char *str) 00022 { 00023 unsigned long hash = 5381; 00024 int c; 00025 while (c = *str++) hash = ((hash << 5) + hash) + c; 00026 return hash; 00027 } 00042 time_queue* time_queue_new(unsigned int size, unsigned int quota) 00043 { 00044 int i; 00045 time_queue* queue = (time_queue*) malloc(sizeof(time_queue)); 00046 queue->values = (unsigned long*) malloc(size * sizeof(long*)); 00047 queue->hashes = (unsigned long*) malloc(size * sizeof(long*)); 00048 queue->size = size; 00049 queue->quota = quota; 00050 queue->i = 0; 00051 for(i = 0; i < size; i++) 00052 { 00053 queue->values[i] = queue->hashes[i] = 0; 00054 } 00055 return queue; 00056 } 00060 unsigned long time_queue_time() 00061 { 00062 struct timeval tv; 00063 gettimeofday(&tv, NULL); 00064 return tv.tv_sec * 1000000 + tv.tv_usec; 00065 } 00075 void time_queue_set(time_queue* queue, char* key) 00076 { 00077 int i, found; 00078 unsigned long hash = time_queue_hash(key); 00079 for(i = found = 0; i < queue->size; i++) 00080 { 00081 if(hash == queue->hashes[i]) 00082 { 00083 found = 1; 00084 break; 00085 } 00086 } 00087 if(!found) 00088 { 00089 queue->i += 1; 00090 queue->i = queue->i % queue->size; 00091 i = queue->i; 00092 queue->hashes[i] = hash; 00093 } 00094 queue->values[i] = time_queue_time(); 00095 } 00110 unsigned long* time_queue_get(time_queue* queue, char* key) 00111 { 00112 int i; 00113 unsigned long hash = time_queue_hash(key); 00114 for(i = 0; i < queue->size; i++) 00115 { 00116 if(hash == queue->hashes[i]) 00117 return queue->values + i; 00118 } 00119 return NULL; 00120 } 00137 int time_queue_overflows(time_queue* queue, char* key, unsigned int size) 00138 { 00139 unsigned long* time = time_queue_get(queue, key); 00140 if(time == NULL) return 0; 00141 unsigned long dt = (time_queue_time() - *time); 00142 if(dt == 0) return 1; 00143 return (((float) size * 1000000 / dt) > ((float)queue->quota)); 00144 } 00149 void time_queue_delete(time_queue* queue) 00150 { 00151 free(queue->values); 00152 free(queue->hashes); 00153 free(queue); 00154 } 00155 /* 00156 * Example: 00157 int main(int argc, char** argv) 00158 { 00159 time_queue* queue = time_queue_new(10, 42); 00160 time_queue_set(queue, "/var/log/lol"); 00161 printf("%lu\n", *time_queue_get(queue, "/var/log/lol")); 00162 sleep(1); 00163 printf("%d\n", time_queue_overflows(queue, "/var/log/lol", 880)); 00164 printf("%lu\n", time_queue_hash("hello world")); 00165 time_queue_delete(queue); 00166 } 00167 */ 00168 #endif