-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiterator_setjmp.c
66 lines (60 loc) · 1.24 KB
/
iterator_setjmp.c
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
#include <stdlib.h>
#include <setjmp.h>
#include "tree.h"
#define STACK_SIZE (1UL << 20)
struct tree_it {
char *k;
char *v;
char *stack;
char *gap;
jmp_buf coroutine;
jmp_buf yield;
};
static void
coroutine(struct tree *t, struct tree_it *it)
{
if (t) {
it->k = t->key;
it->v = t->value;
if (!setjmp(it->coroutine))
longjmp(it->yield, 1);
coroutine(t->left, it);
coroutine(t->right, it);
}
}
static void
coroutine_init(struct tree *t, struct tree_it *it)
{
if (!setjmp(it->coroutine))
longjmp(it->yield, 1);
coroutine(t, it);
longjmp(it->yield, 1);
}
struct tree_it *
tree_iterator(struct tree *t)
{
struct tree_it *it = malloc(sizeof(*it));
it->stack = malloc(STACK_SIZE);
char marker;
char gap[&marker - it->stack - STACK_SIZE];
it->gap = gap; // prevent optimization
if (!setjmp(it->yield))
coroutine_init(t, it);
return it;
}
int
tree_next(struct tree_it *it, char **k, char **v)
{
it->k = 0;
if (!setjmp(it->yield))
longjmp(it->coroutine, 1);
if (it->k) {
*k = it->k;
*v = it->v;
return 1;
} else {
free(it->stack);
free(it);
return 0;
}
}