aboutsummaryrefslogtreecommitdiff
path: root/src/slice.c
blob: eb88f931b6dbdac46087e681aa6f11313e9772cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#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;
}

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;
}