4939a74752
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
64 lines
1.1 KiB
C
64 lines
1.1 KiB
C
#include "buffer.h"
|
|
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
typedef enum {
|
|
BUFFER_FILE,
|
|
BUFFER_STRING
|
|
} BufferType;
|
|
|
|
struct Buffer {
|
|
BufferType type;
|
|
union {
|
|
FILE* file;
|
|
struct {
|
|
const char* data;
|
|
size_t pos;
|
|
} string;
|
|
} source;
|
|
};
|
|
|
|
Buffer* buffer_open_file(const char* path) {
|
|
FILE* f = fopen(path, "r");
|
|
if (f == NULL)
|
|
return NULL;
|
|
Buffer* buf = malloc(sizeof(Buffer));
|
|
if (buf == NULL) {
|
|
fclose(f);
|
|
return NULL;
|
|
}
|
|
buf->type = BUFFER_FILE;
|
|
buf->source.file = f;
|
|
return buf;
|
|
}
|
|
|
|
Buffer* buffer_open_string(const char* string) {
|
|
Buffer* buf = malloc(sizeof(Buffer));
|
|
if (buf == NULL)
|
|
return NULL;
|
|
buf->type = BUFFER_STRING;
|
|
buf->source.string.data = string;
|
|
buf->source.string.pos = 0;
|
|
return buf;
|
|
}
|
|
|
|
void buffer_close(Buffer* buffer) {
|
|
if (buffer->type == BUFFER_FILE)
|
|
fclose(buffer->source.file);
|
|
free(buffer);
|
|
}
|
|
|
|
char buffer_read(Buffer* buffer) {
|
|
if (buffer->type == BUFFER_FILE) {
|
|
int c = fgetc(buffer->source.file);
|
|
return c == EOF ? (char)-1 : (char)c;
|
|
} else {
|
|
char c = buffer->source.string.data[buffer->source.string.pos];
|
|
if (c == '\0')
|
|
return (char)-1;
|
|
buffer->source.string.pos++;
|
|
return c;
|
|
}
|
|
}
|