#include "file.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "error.h"

u8 *sw_file_load(char *path, u32 *out_size) {
	FILE *fil;
	u32 len;
	u8 *data;

	fil = fopen(path, "rb");
	if(!fil) {
		sw_error("Can't load file at \"%s\"", path);
	}
	fseek(fil, 0, SEEK_END);
	len = ftell(fil);
	fseek(fil, 0, SEEK_SET);
	data = malloc(len);
	fread(data, 1, len, fil);
	fclose(fil);

	*out_size = len;
	return data;
}

struct sw_filebuffer *sw_filebuffer_create(u32 size) {
	struct sw_filebuffer *buf;

	buf = malloc(sizeof(struct sw_filebuffer));
	buf->_data = malloc(size);
	buf->size = size;
	buf->pos = 0;

	return buf;
}

struct sw_filebuffer *sw_filebuffer_load(char *path) {
	struct sw_filebuffer *buf;
	u32 size;
	u8 *data;

	data = sw_file_load(path, &size);
	buf = sw_filebuffer_create(size);
	buf->_data = data;

	return buf;
}

void sw_filebuffer_destroy(struct sw_filebuffer *buf) {
	free(buf->_data);
	free(buf);
}

void sw_filebuffer_read(struct sw_filebuffer *buf, void *dst, u32 count) {
	if(buf->pos + count > buf->size) {
		sw_error("read past buffer");
	}
	memcpy(dst, buf->_data + buf->pos, count);
	buf->pos += count;
}
