summaryrefslogtreecommitdiff
path: root/src/runtime/c/gu/choice.c
blob: 5102e15e9b5ca34f4b07847b439f349ec710fb8d (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
#include <gu/choice.h>
#include <gu/seq.h>
#include <gu/assert.h>

struct GuChoice {
	GuBuf* path;
	size_t path_idx;
};

GU_API GuChoice*
gu_new_choice(GuPool* pool)
{
	GuChoice* ch = gu_new(GuChoice, pool);
	ch->path = gu_new_buf(size_t, pool);
	ch->path_idx = 0;
	return ch;
}

GU_API GuChoiceMark
gu_choice_mark(GuChoice* ch)
{
	gu_assert(ch->path_idx <= gu_buf_length(ch->path));
	return (GuChoiceMark){ch->path_idx};
}

GU_API void
gu_choice_reset(GuChoice* ch, GuChoiceMark mark)
{
	gu_assert(ch->path_idx <= gu_buf_length(ch->path));
	gu_require(mark.path_idx <= ch->path_idx );
	ch->path_idx = mark.path_idx;
}

GU_API int
gu_choice_next(GuChoice* ch, int n_choices)
{
	gu_assert(n_choices >= 0);
	gu_assert(ch->path_idx <= gu_buf_length(ch->path));
	if (n_choices == 0) {
		return -1;
	}
	int i = 0;
	if (gu_buf_length(ch->path) > ch->path_idx) {
		i = (int) gu_buf_get(ch->path, size_t, ch->path_idx);
		gu_assert(i <= n_choices);
	} else {
		gu_buf_push(ch->path, size_t, n_choices);
		i = n_choices;
	}
	int ret = (i == 0) ? -1 : n_choices - i;
	ch->path_idx++;
	return ret;
}

GU_API bool
gu_choice_advance(GuChoice* ch)
{
	gu_assert(ch->path_idx <= gu_buf_length(ch->path));
	
	while (gu_buf_length(ch->path) > ch->path_idx) {
		size_t last = gu_buf_pop(ch->path, size_t);
		if (last > 1) {
			gu_buf_push(ch->path, size_t, last-1);
			return true;
		}
	}
	return false;
}