aboutsummaryrefslogtreecommitdiff
path: root/src/slice.c
diff options
context:
space:
mode:
authorYaroslav de la Peña Smirnov <yps@yaroslavps.com>2022-03-24 01:04:02 +0300
committerYaroslav de la Peña Smirnov <yps@yaroslavps.com>2022-03-24 01:04:02 +0300
commit5d66c96a190a396a1535c89bed4e33c2a005fe8d (patch)
tree36a681d8cf226cf30f06b2764c008077d9655dc7 /src/slice.c
downloadroscha-5d66c96a190a396a1535c89bed4e33c2a005fe8d.tar.gz
roscha-5d66c96a190a396a1535c89bed4e33c2a005fe8d.zip
Initial commit
Basically it works, just needs some polishing and maybe a couple of features that I could actually use. Also probably better docs. Not sure if it will be of use to anybody besides me.
Diffstat (limited to 'src/slice.c')
-rw-r--r--src/slice.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/slice.c b/src/slice.c
new file mode 100644
index 0000000..5d89d9e
--- /dev/null
+++ b/src/slice.c
@@ -0,0 +1,63 @@
+#include "slice.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+struct slice
+slice_new(const char *str, size_t start, size_t end)
+{
+ struct slice slice = {
+ .str = str,
+ .start = start,
+ .end = end,
+ };
+
+ return slice;
+}
+
+void
+slice_set(struct slice *slice, const char *str, size_t start, size_t end)
+{
+ slice->str = str;
+ slice->start = start;
+ slice->end = end;
+}
+
+size_t
+slice_len(const struct slice *slice)
+{
+ return slice->end - slice->start;
+}
+
+int
+slice_cmp(const struct slice *restrict a, const struct slice *restrict b)
+{
+ size_t lena = slice_len(a), lenb = slice_len(b);
+ int lencmp = (lena > lenb) - (lena < lenb);
+ if (lencmp) {
+ return lencmp;
+ }
+
+ for (size_t i = 0; i < lena; i++) {
+ char ca = a->str[a->start + i], cb = b->str[b->start + i];
+ int cmp = (ca > cb) - (ca < cb);
+ if (cmp) return cmp;
+ }
+
+ return 0;
+}
+
+void
+slice_cpy(struct slice *dst, const struct slice *src)
+{
+ dst->str = src->str;
+ dst->start = src->start;
+ dst->end = src->end;
+}
+
+sds
+slice_string(const struct slice *slice, sds str)
+{
+ size_t len = slice->end - slice->start;
+ return sdscatlen(str, slice->str + slice->start, len);
+}