From a550c7f22985048a0089a529ca89061ab80daff2 Mon Sep 17 00:00:00 2001 From: Shav Kinderlehrer Date: Mon, 17 Apr 2023 10:23:52 -0400 Subject: Add optional processing stage --- src/lib/file.c | 15 ++++++----- src/lib/process.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 6 deletions(-) create mode 100644 src/lib/process.c (limited to 'src/lib') diff --git a/src/lib/file.c b/src/lib/file.c index f1efa04..f8453d2 100644 --- a/src/lib/file.c +++ b/src/lib/file.c @@ -2,26 +2,29 @@ #include #include -#include "file.h" +#include "types.h" #include "util.h" struct filedata readfile(FILE *fp) { struct filedata f; f.lc = 0; - f.len = 0; + f.buflen = 0; f.binary = 0; + f.buf = NULL; + f.lines = NULL; + // expects to be at beginning of file fseek(fp, 0, SEEK_END); - f.len = ftell(fp); + f.buflen = ftell(fp); fseek(fp, 0, SEEK_SET); - f.buf = malloc(f.len); + f.buf = malloc(f.buflen); if (f.buf == NULL) die("malloc"); - if (fread(f.buf, f.len, 1, fp) < 0) { + if (fread(f.buf, f.buflen, 1, fp) < 0) { die("fread"); } @@ -29,7 +32,7 @@ struct filedata readfile(FILE *fp) { // guess if printable // from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs - int testlen = f.len >= 64 ? 64 : f.len; + int testlen = f.buflen >= 64 ? 64 : f.buflen; char *testbuf[testlen]; memcpy(testbuf, f.buf, testlen); diff --git a/src/lib/process.c b/src/lib/process.c new file mode 100644 index 0000000..61261d9 --- /dev/null +++ b/src/lib/process.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#include "types.h" +#include "util.h" + +void appendline(struct filedata *f, char *data, size_t len) { + f->lines = realloc(f->lines, sizeof(struct line) * (f->lc + 1)); + + size_t loc = f->lc; + + f->lines[loc].len = len; + f->lines[loc].buf = malloc(len + 1); + memcpy(f->lines[loc].buf, data, len); + f->lines[loc].buf[len] = '\0'; +} + +void loadlines(struct filedata *f) { + f->lc = 0; + + size_t offset = 0; + size_t linelen = 4096; + char *line = malloc(linelen); + if (line == NULL) + die("malloc"); + + for (size_t i = 0; i < f->buflen; i++) { + char c = f->buf[i]; + if (c == '\n') { + if (offset < linelen) { + char *new_line = realloc(line, offset); + if (new_line == NULL) + die("realloc"); + line = new_line; + } + + appendline(f, line, offset); + f->lc++; + + free(line); + offset = 0; + line = malloc(linelen); + if (line == NULL) + die("malloc"); + + } else { + if (offset == linelen) { + linelen *= 2; + + char *new_line = realloc(line, linelen); + if (new_line == NULL) + die("realloc"); + + line = new_line; + } + + line[offset++] = c; + } + } +} + +char *linepad(int lc, int total) { + int padlen = intlen(total) - intlen(lc); + char *padding = malloc(padlen + 1); + if (padding == NULL) + die("malloc"); + + if (padlen) + memset(padding, ' ', padlen); + padding[padlen] = '\0'; + + return padding; +} -- cgit v1.2.3