From c0cd4e5f199e8567ec3b5e216fbee27837d21bea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yaroslav=20de=20la=20Pe=C3=B1a=20Smirnov?= Date: Thu, 20 Jan 2022 02:34:32 +0300 Subject: init --- src/slice.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/slice.c (limited to 'src/slice.c') diff --git a/src/slice.c b/src/slice.c new file mode 100644 index 0000000..eb88f93 --- /dev/null +++ b/src/slice.c @@ -0,0 +1,77 @@ +#include "slice.h" + +#include +#include + +struct slice +slice_new(const char *str, size_t start, size_t end) +{ + struct slice slice = { + .str = str, + .start = start, + .end = end, + }; + + return slice; +} + +struct slice +slice_fullstr(const char *str) +{ + struct slice slice = { + .str = str, + .start = 0, + .end = strlen(str), + }; + + 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; +} + +char * +slice_sprint(struct slice *slice, char *str) +{ + size_t len = slice->end - slice->start; + strncpy(str, slice->str + slice->start, len); + str[len] = '\0'; + return str; +} -- cgit v1.2.3