summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lichen.c34
-rw-r--r--lichen.h27
-rw-r--r--lichen.test.c27
3 files changed, 87 insertions, 1 deletions
diff --git a/lichen.c b/lichen.c
index f20c1b3..e8c8e19 100644
--- a/lichen.c
+++ b/lichen.c
@@ -1,4 +1,6 @@
#include "lichen.h"
+#include <stdio.h>
+#include <string.h>
void li_xorshift32_seed(struct li_xorshift32_t *xor, uint32_t seed) {
@@ -18,3 +20,35 @@ uint32_t li_xorshift32(void *s) {
// return just top 32 bits
return x >> 32;
}
+
+
+
+li_llnode_t * li_alloc_llnode() {
+ li_llnode_t *n = malloc(sizeof(li_llnode_t));
+ if (n == NULL) {
+ fprintf(stderr, "failed to allocate linked-list node\n");
+ return NULL;
+ } else {
+ n->tag = 0;
+ n->data = 0;
+ n->next = NULL;
+ return n;
+ }
+}
+
+
+li_llnode_t * li_copy_llnode(li_llnode_t *n) {
+ li_llnode_t *m = li_alloc_llnode();
+ if (m == NULL) {
+ return NULL;
+ }
+ memcpy(m, n, sizeof(li_llnode_t));
+ return m;
+}
+
+void li_free_llnode(li_llnode_t *n, void (*free_data)(void*)) {
+ if (n != NULL) {
+ free_data(n->data);
+ }
+ free(n);
+}
diff --git a/lichen.h b/lichen.h
index fe68d52..b30c8cb 100644
--- a/lichen.h
+++ b/lichen.h
@@ -1,9 +1,10 @@
#ifndef LICHEN_H
#define LICHEN_H
+#include <stdlib.h>
#include <stdint.h>
-// random number generation
+/* --===== random number generation =====-- */
typedef struct li_rand32_t {
uint32_t (*rand)(void *);
void *state;
@@ -21,4 +22,28 @@ void li_xorshift32_seed(struct li_xorshift32_t *xor, uint32_t seed);
uint32_t li_xorshift32(void *s);
+/* --===== generic linked lists =====-- */
+
+
+typedef struct li_llnode_t {
+ int tag;
+ void *data;
+ struct li_llnode_t *next;
+} li_llnode_t;
+
+
+li_llnode_t * li_alloc_llnode();
+li_llnode_t * li_copy_llnode(li_llnode_t *n);
+void li_free_llnode(li_llnode_t *n, void (*free_data)(void*));
+
+
+typedef struct li_ll_t {
+ int tag;
+ size_t count;
+ li_llnode_t *head;
+} li_ll_t;
+
+
+
+
#endif
diff --git a/lichen.test.c b/lichen.test.c
index 77ff067..68d26d0 100644
--- a/lichen.test.c
+++ b/lichen.test.c
@@ -24,6 +24,33 @@ LILY_TEST("xorshift output") {
}
#include LILY_PUSH_TEST()
+
+
+void do_nothing(void *k) {
+ k = k;
+}
+void free_data(void *m) {
+ li_free_llnode(m, do_nothing);
+}
+
+LILY_TEST("allocate, copy, and destroy llnode") {
+ li_llnode_t *n = li_alloc_llnode();
+ REQUIRE_NEQ(n, NULL, "%p");
+ CHECK_EQ(n->next, NULL, "%p");
+ int k = 0;
+ n->tag = 4;
+ n->data = &k;
+ li_llnode_t *m = li_copy_llnode(n);
+ REQUIRE_NEQ(m, NULL, "%p");
+ CHECK_EQ(m->tag, 4, "%d");
+ CHECK_EQ(m->data, &k, "%p");
+ CHECK_EQ(m->next, n->next, "%p");
+ n->data = m;
+ li_free_llnode(n, free_data);
+}
+#include LILY_PUSH_TEST()
+
+
#define LILY_FILE_END
#include LILY_REGISTER_TESTS()