aboutsummaryrefslogtreecommitdiff
path: root/lib.c
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2023-09-02 16:10:59 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2023-09-02 16:14:43 +0100
commitc9b6b04d190c1f9d0c4dfd7c4e66ac0743be18fd (patch)
treeb15cb3c1d407bee7b8dfdd330f46b8cb084328de /lib.c
parentf1891b0c2e85262a8f2dc0a0d13eea192fe00c26 (diff)
downloadobf-c9b6b04d190c1f9d0c4dfd7c4e66ac0743be18fd.tar.gz
obf-c9b6b04d190c1f9d0c4dfd7c4e66ac0743be18fd.tar.bz2
obf-c9b6b04d190c1f9d0c4dfd7c4e66ac0743be18fd.zip
New module for functions I no longer need to work on
lib.(h|c) basically has structures and functions I no longer want to stare at in main.c
Diffstat (limited to 'lib.c')
-rw-r--r--lib.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/lib.c b/lib.c
new file mode 100644
index 0000000..83f3516
--- /dev/null
+++ b/lib.c
@@ -0,0 +1,57 @@
+/* lib.c
+ * Created: 2023-09-02
+ * Author: Aryadev Chavali
+ * Description: General functions used throughout
+ */
+
+#include <string.h>
+
+#include "./lib.h"
+
+buffer_t *buffer_init_str(const char *name, const char *str, size_t str_size)
+{
+ buffer_t *buf = malloc(sizeof(*buf) + str_size + 1);
+ buf->name = name;
+ buf->size = str_size;
+ memcpy(buf->data, str, str_size);
+ buf->data[str_size] = '\0';
+ return buf;
+}
+
+void print_error(const char *handle, size_t row, size_t column,
+ const char *reason)
+{
+ fprintf(stderr, "%s:%lu:%lu:%s\n", handle, row, column, reason);
+}
+
+char *fread_all(FILE *fp)
+{
+ const size_t CHUNK_SIZE = 1024, MULT = 2;
+ struct
+ {
+ char *data;
+ size_t used, available;
+ } buffer = {calloc(CHUNK_SIZE, sizeof(*buffer.data)), 0, CHUNK_SIZE};
+
+ size_t acc = 0, bytes_read = 0;
+ while ((bytes_read = fread(buffer.data + acc, sizeof(*buffer.data),
+ CHUNK_SIZE, fp)) != 0)
+ {
+ buffer.used += bytes_read;
+ acc += bytes_read;
+ if (buffer.used + CHUNK_SIZE >= buffer.available)
+ {
+ buffer.available = MAX(buffer.available * MULT, buffer.used + CHUNK_SIZE);
+ buffer.data = realloc(buffer.data, buffer.available);
+ }
+ }
+ buffer.data = realloc(buffer.data, buffer.used + 1);
+ buffer.data[buffer.used] = '\0';
+ return buffer.data;
+}
+
+bool usable_character(char c)
+{
+ return c == '>' || c == '<' || c == '+' || c == '-' || c == '-' || c == '.' ||
+ c == ',' || c == '[' || c == ']';
+}