calc

Simple math expression parser.
git clone git://git.amin.space/calc.git
Log | Files | Refs | LICENSE

commit bf20c5c23810b4a852423febc93931293b4d0f93
parent b2a64e2fba3f7ad8b9ad55fcb0c718d4eb9c7859
Author: amin <dev@aminmesbah.com>
Date:   Sat, 27 Oct 2018 03:46:24 +0000

Make a stretchy buf

FossilOrigin-Name: 28b3afc7914d9a89e792c00999e749d9fd5b25c01e992e13954ed9289378826d
Diffstat:
Mcalc.c | 57++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 56 insertions(+), 1 deletion(-)

diff --git a/calc.c b/calc.c @@ -1,6 +1,61 @@ +#include <assert.h> +#include <stddef.h> +#include <stdint.h> #include <stdio.h> +#include <stdlib.h> + +struct BufHdr { + size_t cap; + size_t len; + uint8_t buf[]; +}; + +#define buf__hdr(b) ((struct BufHdr *)((uint8_t *)(b) - offsetof(struct BufHdr, buf))) +#define buf_cap(b) ((b) ? buf__hdr(b)->cap : 0) +#define buf_len(b) ((b) ? buf__hdr(b)->len : 0) + +#define buf__must_grow(b, n) (buf_len(b) + (n) >= buf_cap(b)) +#define buf__maybe_grow(b, n) (buf__must_grow((b), (n)) ? (b) = buf__grow((b), buf_len(b) + (n), sizeof(*(b))) : 0) +#define buf_push(b, x) (buf__maybe_grow((b), 1), (b)[buf__hdr(b)->len++] = (x)) + +#define MAX(x, y) ((x) >= (y) ? (x) : (y)) + +void *buf__grow(void *buf, size_t new_length, size_t element_size) +{ + size_t new_cap = MAX(1 + (2 * buf_cap(buf)), new_length); + assert(new_cap >= new_length); + size_t new_size = offsetof(struct BufHdr, buf) + (new_cap * element_size); + struct BufHdr *new_hdr = NULL; + if (buf) + { + new_hdr = realloc(buf__hdr(buf), new_size); + } + else + { + new_hdr = malloc(new_size); + new_hdr->len = 0; + } + new_hdr->cap = new_cap; + return new_hdr->buf; +} + +void buf_test(void) +{ + int *buf = NULL; + assert(buf_len(buf) == 0); + for (size_t i = 0; i < 1000; ++i) + { + buf_push(buf, i); + } + assert(buf_len(buf) == 1000); + for (size_t i = 0; i < buf_len(buf); ++i) + { + printf("%d, ", buf[i]); + } + printf("\n"); +} int main(void) { - printf("Hello, world"); + buf_test(); }