summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore4
-rw-r--r--array.c38
-rw-r--r--array.h14
3 files changed, 37 insertions, 19 deletions
diff --git a/.gitignore b/.gitignore
index 567609b..0376683 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,5 @@
build/
+tests/
+*.out
+*.a
+*.so
diff --git a/array.c b/array.c
index c7df5b5..d8765c1 100644
--- a/array.c
+++ b/array.c
@@ -1,29 +1,39 @@
#include "array.h"
#include "crash.h"
+#include <string.h>
+
#define CRASH_IF_OOB(array, idx) {\
if (idx >= array->length)\
crash("Array access out of bounds: %ld >= %ld\n", idx, array->length);\
}
-void array_set(array_t* array, size_t idx, void* val) {
- CRASH_IF_OOB(array, idx);
- char* data_ptr = (char*)array->__data + idx*array->elemsz;
- for (size_t i = 0; i < array->elemsz; i++) {
- data_ptr[i] = *((char*)val + i);
- }
-}
-
-void* array_get(const array_t* array, size_t idx) {
+void* array_at(const array_t* array, size_t idx) {
CRASH_IF_OOB(array, idx);
return (char*)array->__data + idx*array->elemsz;
}
-void str_set(str_t* str, size_t idx, char val) {
+char* str_at(const str_t* str, size_t idx) {
CRASH_IF_OOB(str, idx);
- str->__data[idx] = val;
+ return str->__data + idx;
}
-char str_get(const str_t* str, size_t idx) {
- CRASH_IF_OOB(str, idx);
- return str->__data[idx];
+str_t str_slice(const str_t* str, size_t start, size_t length) {
+ CRASH_IF_OOB(str, start + length - 1);
+ str_t slice = {.length = length, .__data = str->__data + start};
+ return slice;
+}
+
+void str_c_str(
+ char* dst,
+ size_t dst_size,
+ const str_t* src
+) {
+ if (src->length >= dst_size)
+ crash(
+ "String is too long to hold in C string buffer: %ld >= %ld\n",
+ src->length,
+ dst_size);
+
+ memmove(dst, src->__data, src->length);
+ dst[src->length] = 0;
}
diff --git a/array.h b/array.h
index 2741ed0..5634dc7 100644
--- a/array.h
+++ b/array.h
@@ -8,16 +8,20 @@ typedef struct {
void* __data;
} array_t;
-void array_set(array_t* array, size_t idx, void* val);
-void* array_get(const array_t* array, size_t idx);
+void* array_at(const array_t* array, size_t idx);
typedef struct {
size_t length;
char* __data;
} str_t;
-void str_set(str_t* str, size_t idx, char val);
-char str_get(const str_t* str, size_t idx);
-/* TODO: I would like to implement string slicing as part of this */
+char* str_at(const str_t* str, size_t idx);
+str_t str_slice(const str_t* str, size_t start, size_t length);
+void str_c_str(
+ char* dst,
+ size_t dst_size,
+ const str_t* src
+);
+
/* TODO: reimplement string.h functions for this new string construct */
#endif