aboutsummaryrefslogtreecommitdiff
path: root/example_hashmap/new/main.c
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2025-08-30 00:01:15 +0300
committerKimplul <kimi.h.kuparinen@gmail.com>2025-08-30 00:01:15 +0300
commit20ce6fa81cd9f55dca3212699d5949f8ebe7d95b (patch)
treefdb89a8b290668ef61cc4747ac5236b817fdd686 /example_hashmap/new/main.c
parent9a31a10d18ff5de50b4532a7f461ec97c5880d11 (diff)
downloadngc-20ce6fa81cd9f55dca3212699d5949f8ebe7d95b.tar.gz
ngc-20ce6fa81cd9f55dca3212699d5949f8ebe7d95b.zip
add hashmap example
+ Doesn't quite work yet because <type> expansion isn't implemented yet
Diffstat (limited to 'example_hashmap/new/main.c')
-rw-r--r--example_hashmap/new/main.c62
1 files changed, 62 insertions, 0 deletions
diff --git a/example_hashmap/new/main.c b/example_hashmap/new/main.c
new file mode 100644
index 0000000..4846ab5
--- /dev/null
+++ b/example_hashmap/new/main.c
@@ -0,0 +1,62 @@
+#include <assert.h>
+#include <stdio.h>
+
+#include "map.h"
+
+#define foreach(name, i, s) \
+ for (name##_iter i = name##_begin(s); !name##_end(s, i); i = name##_next(i))
+
+/* int wrapper, provides cmp/hash for a generic integer type
+ * (here a trait like is_integer would be ideal but oh well) */
+typedef intw[any I]() {
+ typedef I <>;
+
+ size_t <>_hash(<> *a)
+ {
+ /* identity hash */
+ return *a;
+ }
+
+ int <>_cmp(<> *a, <> *b)
+ {
+ return *a - *b;
+ }
+};
+
+/* create wrapper for ints. */
+typedef intw = intw[int]();
+
+/* create hashmap of ints, using the intw wrapper we just created. Kind of
+ * boilerplatey, admittedly. */
+typedef ints = map[intw, intw]();
+
+int main()
+{
+ /* heuristic, but if we know how many elements we'll need, we should
+ * give it to the create function. */
+ ints ints = ints_create(0);
+ for (int i = 0; i < 1000000; ++i) {
+ ints_insert(&ints, i, i);
+ }
+ assert(ints_len(&ints) == 1000000);
+
+ for (int i = 0; i < 1000000; ++i) {
+ int *v = ints_find(&ints, i);
+ assert(v && *v == i);
+ }
+
+ size_t count = 0;
+ foreach(ints, iter, &ints) {
+ assert(iter->key == iter->data);
+ count++;
+ }
+
+ assert(count == 1000000);
+
+ for (int i = 0; i < 1000000; ++i) {
+ ints_remove(&ints, i);
+ }
+
+ assert(ints_len(&ints) == 0);
+ ints_destroy(&ints);
+}