63 lines
1.3 KiB
C
63 lines
1.3 KiB
C
/*
|
|
*
|
|
* 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];
|
|
size_t rsize = read(cache->fd, buffer, sizeof(buffer));
|
|
|
|
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;
|
|
}
|
|
return (char)cache->data[cache->rpos++];
|
|
}
|
|
|
|
|
|
void rcache_destroy(rcache_t * cache) {
|
|
if (cache != NULL) {
|
|
free(cache->data);
|
|
}
|
|
}
|