From e68480f2fc508ce73cad331ce4e8439e07d25702 Mon Sep 17 00:00:00 2001 From: Kimplul Date: Mon, 1 Sep 2025 22:00:02 +0300 Subject: use <> as expansion characters + I kind of like the 'symmetry' of <> being 'self' and being some parameter, but having to type lots of extra <*> is a bit annoying, and might also be an issue for C++. Still, enough functionality for a hashmap example --- example_vec/new/main.c | 15 ++++++++++++--- example_vec/new/vec.h | 18 +++++++++--------- 2 files changed, 21 insertions(+), 12 deletions(-) (limited to 'example_vec/new') diff --git a/example_vec/new/main.c b/example_vec/new/main.c index 4849cb3..a756281 100644 --- a/example_vec/new/main.c +++ b/example_vec/new/main.c @@ -1,12 +1,21 @@ #include + +/* an empty trait matches anything, this would presumably be defined in a + * library somewhere and then included everywhere */ +typedef any {} + #include "vec.h" #define foreach(name, i, s) \ for (name##_iter i = name##_begin(s); !name##_end(s, i); i = name##_next(i)) -typedef summable_vec[summable type]() = vec[type](){ - type <>_sum(struct <> *v) { - type sum = 0; +/* traits aren't really implemented fully yet but this would check for a + * function like <>_add(<> a, <> b) or something along those lines */ +typedef summable {} + +typedef summable_vec[summable type]() = vec[](){ + <>_sum(struct <> *v) { + sum = 0; for (size_t i = 0; i < v->n; ++i) { sum += v->buf[i]; } diff --git a/example_vec/new/vec.h b/example_vec/new/vec.h index 613af51..6842a42 100644 --- a/example_vec/new/vec.h +++ b/example_vec/new/vec.h @@ -10,10 +10,10 @@ typedef vec[any type]() { struct <> { size_t n; size_t s; - type *buf; + *buf; }; - typedef type *<>_iter; + typedef *<>_iter; struct <> <>_create(size_t reserve) { @@ -23,7 +23,7 @@ typedef vec[any type]() { return (struct <>){ .n = 0, .s = reserve, - .buf = malloc(reserve * sizeof(type)) + .buf = malloc(reserve * sizeof()) }; } @@ -38,25 +38,25 @@ typedef vec[any type]() { } - type *<>_at(struct <> *v, size_t i) + *<>_at(struct <> *v, size_t i) { assert(i < v->n && "out of vector bounds"); return &v->buf[i]; } - type *<>_pop(struct <> *v) + *<>_pop(struct <> *v) { assert(v->n && "attempting to pop empty vector"); v->n--; return &v->buf[v->n]; } - type* <>_append(struct <> *v, type n) + * <>_append(struct <> *v, n) { v->n++; if (v->n >= v->s) { v->s = v->s == 0 ? 1 : 2 * v->s; - v->buf = realloc(v->buf, v->s * sizeof(type)); + v->buf = realloc(v->buf, v->s * sizeof()); } v->buf[v->n - 1] = n; @@ -80,7 +80,7 @@ typedef vec[any type]() { while (v->s < v->n) v->s = v->s == 0 ? 1 : 2 * v->s; - v->buf = realloc(v->buf, v->s * sizeof(type)); + v->buf = realloc(v->buf, v->s * sizeof()); } void <>_shrink(struct <> *v, size_t n) @@ -92,7 +92,7 @@ typedef vec[any type]() { void <>_remove(struct <> *v, size_t i) { assert(v->n > i); - size_t c = sizeof(type) * (v->n - i); + size_t c = sizeof() * (v->n - i); memcpy(&v->buf[i], &v->buf[i + 1], c); v->n--; } -- cgit v1.2.3