typedef struct k_cache_struct
{
uint8_t *buf;
int32_t vol;
int32_t in;
int32_t out;
int32_t flag;
}k_cache_t;
enum k_cache_flag
{
CACHE_INIT = 0,
CACHE_END,
CACHE_ERR,
};
static int32_t k_cache_size_data(k_cache_t *cache)
{
int32_t tmp = cache->in - cache->out;
if(tmp < 0)
{
return tmp + cache->vol;
}
return tmp;
}
static int32_t k_cache_size_empty(k_cache_t *cache)
{
int32_t tmp = cache->out - cache->in;
if(tmp <= 0)
{
tmp += cache->vol;
}
tmp = tmp > 4 ? tmp - 4 : 0;
return tmp;
}
int32_t k_cache_init(k_cache_t *cache, void *buf, int32_t size)
{
cache->buf = buf;
cache->vol = size;
cache->in = 0;
cache->out = 0;
cache->flag = CACHE_INIT;
return 0;
}
int32_t k_cache_read(k_cache_t *cache, void *buf, int32_t size)
{
int32_t i, rev;
uint8_t *dst;
while(1)
{
rev = k_cache_size_data(cache);
if(rev >= size)
{
rev = size;
break;
}
else if(cache->flag == CACHE_END)
{
size = rev;
break;
}
else if(cache->flag == CACHE_ERR)
{
printf("[cache]cache read err\n");
return -1;
}
os_thread_sleep(10);
}
i = cache->out;
dst = (uint8_t *)buf;
while(rev > 0)
{
*dst++ = cache->buf[i++];
if(i >= cache->vol){
i = 0;
}
rev--;
}
cache->out = i;
return size;
}
int32_t k_cache_write(k_cache_t *cache, void *buf, int32_t size)
{
int32_t i, rev;
uint8_t *src;
#if 0
while(1)
{
rev = k_cache_size_empty(cache);
if(rev >= size)
{
rev = size;
break;
}
else if(cache->flag == CACHE_END)
{
size = rev;
break;
}
else if(cache->flag == CACHE_ERR)
{
printf("[cache]cache write err\n");
return -1;
}
os_thread_sleep(10);
}
#else
rev = k_cache_size_empty(cache);
if(rev >= size)
{
rev = size;
}
else if(cache->flag == CACHE_END)
{
return 0;
}
else if(cache->flag == CACHE_ERR)
{
printf("[cache]cache write err\n");
return -1;
}
else
{
return 0;
}
#endif
i = cache->in;
src = (uint8_t *)buf;
while(rev > 0)
{
cache->buf[i++] = *src++;
if(i >= cache->vol){
i = 0;
}
rev--;
}
cache->in = i;
return size;
}
void k_cache_set_end(k_cache_t *cache)
{
cache->flag = CACHE_END;
}
void k_cache_set_err(k_cache_t *cache)
{
cache->flag = CACHE_ERR;
}
int32_t k_cache_flag_get(k_cache_t *cache)
{
return cache->flag;
}
k_cache_t cache = {0};
void main(void)
{
uint8_t *buf = (uint8_t *)malloc(1024);
if(buf == NULL)
return;
k_cache_init(&cache, buf, 1024);
uint8_t *write_buf = (uint8_t *)malloc(64);
if(write_buf == NULL)
return;
memset(write_buf, 0x55, 64);
uint8_t *read_buf = (uint8_t *)malloc(64);
if(read_buf == NULL)
return;
while(1)
{
k_cache_write(&cache, write_buf ,64);
k_cache_read(&cache, read_buf ,64);
os_thread_sleep(10);
}
return;
}