#include "lafe_platform.h"
__FBSDID("$FreeBSD$");
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "err.h"
#include "line_reader.h"
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__)
#define strdup _strdup
#endif
struct lafe_line_reader {
FILE *f;
char *buff, *buff_end, *line_start, *line_end, *p;
char *pathname;
size_t buff_length;
int nullSeparator;
int ret;
};
struct lafe_line_reader *
lafe_line_reader(const char *pathname, int nullSeparator)
{
struct lafe_line_reader *lr;
lr = calloc(1, sizeof(*lr));
if (lr == NULL)
lafe_errc(1, ENOMEM, "Can't open %s", pathname);
lr->nullSeparator = nullSeparator;
lr->pathname = strdup(pathname);
if (strcmp(pathname, "-") == 0)
lr->f = stdin;
else
lr->f = fopen(pathname, "r");
if (lr->f == NULL)
lafe_errc(1, errno, "Couldn't open %s", pathname);
lr->buff_length = 8192;
lr->buff = malloc(lr->buff_length);
if (lr->buff == NULL)
lafe_errc(1, ENOMEM, "Can't read %s", pathname);
lr->line_start = lr->line_end = lr->buff_end = lr->buff;
return (lr);
}
const char *
lafe_line_reader_next(struct lafe_line_reader *lr)
{
size_t bytes_wanted, bytes_read, new_buff_size;
char *line_start, *p;
for (;;) {
while (lr->line_end < lr->buff_end) {
if (lr->nullSeparator) {
if (*lr->line_end == '\0') {
line_start = lr->line_start;
lr->line_start = lr->line_end + 1;
lr->line_end = lr->line_start;
return (line_start);
}
} else if (*lr->line_end == '\x0a' || *lr->line_end == '\x0d') {
*lr->line_end = '\0';
line_start = lr->line_start;
lr->line_start = lr->line_end + 1;
lr->line_end = lr->line_start;
if (line_start[0] != '\0')
return (line_start);
}
lr->line_end++;
}
if (lr->f == NULL) {
if (lr->line_end > lr->line_start) {
*lr->line_end = '\0';
line_start = lr->line_start;
lr->line_start = lr->line_end + 1;
lr->line_end = lr->line_start;
return (line_start);
}
return (NULL);
}
if (lr->line_start > lr->buff) {
memmove(lr->buff, lr->line_start,
lr->buff_end - lr->line_start);
lr->buff_end -= lr->line_start - lr->buff;
lr->line_end -= lr->line_start - lr->buff;
lr->line_start = lr->buff;
} else {
new_buff_size = lr->buff_length * 2;
if (new_buff_size <= lr->buff_length)
lafe_errc(1, ENOMEM,
"Line too long in %s", lr->pathname);
lr->buff_length = new_buff_size;
p = realloc(lr->buff, new_buff_size);
if (p == NULL)
lafe_errc(1, ENOMEM,
"Line too long in %s", lr->pathname);
lr->buff_end = p + (lr->buff_end - lr->buff);
lr->line_end = p + (lr->line_end - lr->buff);
lr->line_start = lr->buff = p;
}
bytes_wanted = lr->buff + lr->buff_length - lr->buff_end;
bytes_read = fread(lr->buff_end, 1, bytes_wanted, lr->f);
lr->buff_end += bytes_read;
if (ferror(lr->f))
lafe_errc(1, errno, "Can't read %s", lr->pathname);
if (feof(lr->f)) {
if (lr->f != stdin)
fclose(lr->f);
lr->f = NULL;
}
}
}
void
lafe_line_reader_free(struct lafe_line_reader *lr)
{
free(lr->buff);
free(lr->pathname);
free(lr);
}