at work
This commit is contained in:
65
clib/rcache.c
Normal file
65
clib/rcache.c
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2023 Oleg Borodin <borodin@unix7.org>
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#include <rcache.h>
|
||||
|
||||
|
||||
#define CACHE_INITCAPA 512
|
||||
|
||||
rcache_t* rcache_init(rcache_t * cache, int fd) {
|
||||
cache->data = malloc(CACHE_INITCAPA);
|
||||
if (cache->data == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
cache->wpos = 0;
|
||||
cache->rpos = 0;
|
||||
cache->capa = CACHE_INITCAPA;
|
||||
cache->fd = fd;
|
||||
return cache;
|
||||
}
|
||||
|
||||
#define BUFFER_SIZE 1024
|
||||
|
||||
char rcache_getc(rcache_t * cache) {
|
||||
size_t unread = cache->wpos - cache->rpos;
|
||||
|
||||
if (unread == 0) {
|
||||
char* buffer[BUFFER_SIZE];
|
||||
ssize_t rsize = read(cache->fd, buffer, sizeof(buffer));
|
||||
if (rsize < 0) {
|
||||
return EOF;
|
||||
}
|
||||
if (rsize == 0) {
|
||||
return EOF;
|
||||
}
|
||||
if ((cache->wpos + rsize) > cache->capa) {
|
||||
size_t newcapa = cache->capa * 2 + rsize;
|
||||
uint8_t* newdata = realloc(cache->data, (size_t)newcapa);
|
||||
|
||||
if (newdata == NULL) {
|
||||
return (ssize_t) - 1;
|
||||
}
|
||||
cache->data = newdata;
|
||||
cache->capa = newcapa;
|
||||
}
|
||||
memcpy(&(cache->data[cache->wpos]), buffer, (size_t)rsize);
|
||||
cache->wpos += rsize;
|
||||
}
|
||||
//printf("[%c]", (char)cache->data[cache->rpos]);
|
||||
return (char)cache->data[cache->rpos++];
|
||||
}
|
||||
|
||||
|
||||
void rcache_destroy(rcache_t * cache) {
|
||||
if (cache != NULL) {
|
||||
free(cache->data);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user