feat: implement file writer
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#include <compiler/fzl_writer.h>
|
||||
#include <compiler/utils/fzl_const_pool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
char wrlast_err[256];
|
||||
|
||||
fzl_writer_t *fzl_mkwriter(const char *filepath)
|
||||
{
|
||||
if (strlen(filepath) < 1)
|
||||
return NULL;
|
||||
|
||||
fzl_writer_t *writer = malloc(sizeof(fzl_writer_t));
|
||||
if (!writer)
|
||||
return NULL;
|
||||
|
||||
writer->filepath = filepath;
|
||||
|
||||
return writer;
|
||||
}
|
||||
|
||||
int fzl_write(fzl_writer_t *writer, fzl_walker_t *walker)
|
||||
{
|
||||
if (!writer || !walker)
|
||||
return -1;
|
||||
|
||||
FILE *fp = fopen(writer->filepath, "wb");
|
||||
if (!fp)
|
||||
{
|
||||
snprintf(wrlast_err, sizeof(wrlast_err), "failed to open '%s' to write",
|
||||
writer->filepath);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char hdr[5] = {'F', 'Z', 'L', 0x0, 0x1};
|
||||
fwrite(hdr, sizeof(char), 5, fp);
|
||||
fwrite(&walker->consts->size, sizeof(size_t), 1, fp);
|
||||
fwrite(&walker->op_count, sizeof(size_t), 1, fp);
|
||||
|
||||
for (size_t i = 0; i < walker->consts->size; i++)
|
||||
{
|
||||
fzl_const_t c = walker->consts->array[i];
|
||||
fwrite(&c.type, sizeof(fzl_consttype_t), 1, fp);
|
||||
|
||||
if (c.type == FZL_CONSTTYPE_STRING)
|
||||
{
|
||||
size_t strlen = c.as.string.length;
|
||||
fwrite(&c.as.string.length, sizeof(size_t), 1, fp);
|
||||
fwrite(c.as.string.chars, sizeof(char), strlen, fp);
|
||||
}
|
||||
}
|
||||
|
||||
if (walker->op_count > 0)
|
||||
fwrite(walker->ops, sizeof(uint64_t), walker->op_count, fp);
|
||||
|
||||
fclose(fp);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
char *fzl_writer_geterror() { return wrlast_err; }
|
||||
|
||||
void fzl_freewriter(fzl_writer_t *writer)
|
||||
{
|
||||
if (!writer)
|
||||
return;
|
||||
|
||||
free(writer);
|
||||
}
|
||||
Reference in New Issue
Block a user