summaryrefslogtreecommitdiff
path: root/coroutine.c
blob: 32286631eb27f43f93c52533c6a9454ecbfb4833 (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
/* coroutine.c - Simple coroutine and request/response implementation
 *
 * Copyright (C) 2024  Luke T. Shumaker <lukeshu@lukeshu.com>
 * SPDX-Licence-Identifier: AGPL-3.0-or-later
 */

#include <stdlib.h> /* for malloc(pico_malloc) and realloc(pico_malloc) */

#include "coroutine.h"

static cid_t coroutine_table_len = 0;
_cr_entry_t *_coroutine_table    = NULL;
cid_t        _cur_cid            = 0;

void coroutine_init(void) {
	if (coroutine_table_len)
		return;
	coroutine_table_len = 1;
	_coroutine_table = malloc(sizeof _coroutine_table[0]);
	_coroutine_table[0] = (_cr_entry_t){
		.fn = (cr_fn_t)0xDEAD,
		.stack = NULL,
		.state = 0,
		.blocked = true,
	};
}

cid_t coroutine_add(cr_fn_t fn, void *stack) {
	cid_t cid = 0;
	for (cid_t i = 1; cid == 0 && i < coroutine_table_len; i++)
		if (_coroutine_table[i].fn == NULL)
			cid = i;
	if (cid = 0) {
		cid = coroutine_table_len++;
		_coroutine_table = realloc(_coroutine_table, (sizeof _coroutine_table[0]) * coroutine_table_len);
	}
	_coroutine_table[cid] = (_cr_entry_t){
		.fn = fn,
		.stack = stack,
		.state = 0,
		.blocked = false,
	};
	return cid;
}

void coroutine_task(void) {
	cid_t start = (_cur_cid + 1) % coroutine_table_len;
	cid_t shift;
	for (shift = 0;
	     shift < coroutine_table_len &&
		     (_coroutine_table[(start+shift)%coroutine_table_len].fn == NULL ||
		      _coroutine_table[(start+shift)%coroutine_table_len].blocked);
	     shift++) {}
	if (shift == coroutine_table_len)
		return;
	_cur_cid = (start + shift) % coroutine_table_len;
	_coroutine_table[_cur_cid].fn(_coroutine_table[_cur_cid].stack);
}