aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorErik Liodden <eriklio@stud.ntnu.no>2017-11-15 15:56:36 +0100
committerErik Liodden <eriklio@stud.ntnu.no>2017-11-15 15:59:55 +0100
commitbc8c1f71b027bebafe98deddbdc7d2b98b12c253 (patch)
tree68dc5606f88b4112d6a95527dfe8878d8395ba65
parentd654d0885efdedc8c16b8cecd6008663466d7d9b (diff)
downloadalgdat-bc8c1f71b027bebafe98deddbdc7d2b98b12c253.tar.gz
add various helper functions
add allocate, swap and rotate.
-rw-r--r--include/misc.h28
-rw-r--r--src/misc/misc.c52
2 files changed, 80 insertions, 0 deletions
diff --git a/include/misc.h b/include/misc.h
new file mode 100644
index 0000000..7dc7387
--- /dev/null
+++ b/include/misc.h
@@ -0,0 +1,28 @@
+/*
+ * misc.h
+ * decleration of various helper and misc functions
+ *
+ * Erik Liodden
+ */
+
+#ifndef MISC_H
+#define MISC_H
+
+/*
+ * allocate `size` bytes and return a pointer to the allocated memory. if the
+ * memory can't be allocated, the function will terminate the program.
+ */
+void *allocate(size_t size);
+
+/*
+ * swap two pointers
+ */
+void swap(void *vp1, void *vp2, size_t elem_size);
+
+/*
+ * rotate the first segment between `start` and `middle` after the remaining
+ * part of the array
+ */
+void rotate(void *start, void *middle, void *end);
+
+#endif /* MISC_H */
diff --git a/src/misc/misc.c b/src/misc/misc.c
new file mode 100644
index 0000000..bc5a584
--- /dev/null
+++ b/src/misc/misc.c
@@ -0,0 +1,52 @@
+/*
+ * misc.c
+ * decleration of various helper and misc functions
+ *
+ * Erik Liodden
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+/*
+ * allocate `size` bytes and return a pointer to the allocated memory. if the
+ * memory can't be allocated, the function will terminate the program.
+ */
+void *allocate(size_t size)
+{
+ void *result = malloc(size);
+ if (result == NULL) {
+ perror("unable to allocate memory");
+ exit(EXIT_FAILURE);
+ }
+ return result;
+}
+
+/*
+ * swap two pointers
+ */
+void swap(void *vp1, void *vp2, size_t elem_size)
+{
+ void *tmp = allocate(elem_size);
+ memcpy(tmp, vp1, elem_size);
+ memcpy(vp1, vp2, elem_size);
+ memcpy(vp2, tmp, elem_size);
+ free(tmp);
+}
+
+/*
+ * rotate the first segment between `start` and `middle` after the remaining
+ * part of the array
+ */
+void rotate(void *start, void *middle, void *end)
+{
+ int front = (char *)middle - (char *)start;
+ int back = (char *)end - (char *)middle;
+ char *buf = allocate(front);
+
+ memcpy(buf, start, front);
+ memmove(start, middle, back);
+ memcpy((char *)start + back, buf, front);
+}