85 lines
1.9 KiB
C
85 lines
1.9 KiB
C
#include "device.h"
|
|
#include <string.h>
|
|
|
|
void input_init(InputBuffer *input)
|
|
{
|
|
memset(input, 0, sizeof(*input));
|
|
}
|
|
|
|
static int input_refill(FILE *stream, InputBuffer *input)
|
|
{
|
|
if (input->failed || input->ended) {
|
|
return 0;
|
|
}
|
|
input->cursor = 0;
|
|
input->available = fread(input->bytes, 1, sizeof(input->bytes), stream);
|
|
if (input->available != 0) {
|
|
return 1;
|
|
}
|
|
if (ferror(stream)) {
|
|
input->failed = 1;
|
|
} else {
|
|
input->ended = 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int input_byte(FILE *stream, InputBuffer *input, unsigned char *byte)
|
|
{
|
|
if (input->cursor == input->available) {
|
|
if (!input_refill(stream, input)) {
|
|
return 0;
|
|
}
|
|
}
|
|
*byte = input->bytes[input->cursor];
|
|
input->cursor += 1;
|
|
return 1;
|
|
}
|
|
|
|
static InputResult input_finish(char *line, size_t size, int rejected)
|
|
{
|
|
line[size] = '\0';
|
|
if (rejected) {
|
|
return INPUT_REJECTED;
|
|
}
|
|
return INPUT_READY;
|
|
}
|
|
|
|
InputResult input_next(FILE *stream, InputBuffer *input, char *line, size_t capacity)
|
|
{
|
|
if (capacity < 2) {
|
|
return INPUT_FAILED;
|
|
}
|
|
size_t size = 0;
|
|
int rejected = 0;
|
|
int seen = 0;
|
|
for (;;) {
|
|
unsigned char byte;
|
|
if (!input_byte(stream, input, &byte)) {
|
|
if (input->failed) {
|
|
return INPUT_FAILED;
|
|
}
|
|
if (!seen) {
|
|
return INPUT_END;
|
|
}
|
|
return input_finish(line, size, rejected);
|
|
}
|
|
seen = 1;
|
|
if (byte == '\n') {
|
|
return input_finish(line, size, rejected);
|
|
}
|
|
if (byte == 0) {
|
|
rejected = 1;
|
|
continue;
|
|
}
|
|
if (size + 1 == capacity) {
|
|
rejected = 1;
|
|
continue;
|
|
}
|
|
if (!rejected) {
|
|
line[size] = (char)byte;
|
|
size += 1;
|
|
}
|
|
}
|
|
}
|