iris

small scheme interpreter
git clone git://git.2f30.org/iris
Log | Files | Refs | LICENSE

commit bebc3700274e39d89ee2eda2f01c6e20fa41bf07
parent 973134dd5a1b08a04fe438b5fb333c6ab735a89e
Author: sin <sin@2f30.org>
Date:   Fri,  9 May 2014 16:52:42 +0100

Add util

Diffstat:
MMakefile | 2+-
Mrepl.c | 6++++--
Autil.c | 27+++++++++++++++++++++++++++
Autil.h | 4++++
4 files changed, 36 insertions(+), 3 deletions(-)

diff --git a/Makefile b/Makefile @@ -1,6 +1,6 @@ BIN = iris VER = 0.0 -SRC = debug.c lexer.c parser.c repl.c +SRC = debug.c lexer.c parser.c repl.c util.c OBJ = ${SRC:.c=.o} CC = gcc diff --git a/repl.c b/repl.c @@ -4,11 +4,13 @@ #include <string.h> #include "lexer.h" #include "debug.h" +#include "util.h" int main(void) { - char buf[BUFSIZ]; + char *buf = NULL; + size_t sz = 0; struct tok tok; struct lexerctx ctx; @@ -16,7 +18,7 @@ main(void) do { printf("> "); fflush(stdout); - if (fgets(buf, sizeof(buf), stdin)) { + if (afgets(&buf, &sz, stdin)) { resetlexer(&ctx); do { tok = gettok(&ctx, buf, strlen(buf)); diff --git a/util.c b/util.c @@ -0,0 +1,27 @@ +/* See LICENSE file for copyright and license details. */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +char * +afgets(char **p, size_t *size, FILE *fp) +{ + char buf[BUFSIZ]; + size_t n, len = 0; + + while(fgets(buf, sizeof buf, fp)) { + len += (n = strlen(buf)); + if(len + 1 > *size && !(*p = realloc(*p, len + 1))) { + perror("realloc"); + exit(EXIT_FAILURE); + } + + memcpy(&(*p)[len - n], buf, n); + (*p)[len] = '\0'; + + if(buf[n - 1] == '\n' || feof(fp)) + break; + } + + return (len > 0) ? *p : NULL; +} diff --git a/util.h b/util.h @@ -0,0 +1,4 @@ +/* See LICENSE file for copyright and license details. */ +#define LEN(x) (sizeof (x) / sizeof *(x)) + +char *afgets(char **, size_t *, FILE *);