summaryrefslogtreecommitdiff
path: root/src/libc/select.c
blob: 20f7b719e5fc7caf473885143379e1fad5f60801 (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
#include <errno.h>
#include <sys/select.h>
#include <stdio.h>

static int
countset(int nfds, fd_set *set)
{
	int count = 0;
	if (set == NULL) return 0;
	for (int i = 0; i < nfds; i++) {
		if (FD_ISSET(i, set)) {
			count++;
		}
	}
	return count;
}

int
select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
	(void)timeout;
	FD_ZERO(exceptfds);
	if (countset(nfds, readfds) != 0) {
		if (countset(nfds, readfds) == 1 && countset(nfds, writefds) == 0) {
			/* special case: if you're only waiting for a single fd to become
			 * readable, just go ahead and read() it.
			 * curl compat. */
			return 1;
		}
		return errno = ENOSYS, -1;
	}
	return countset(nfds, writefds); /* assume everything is ready for writing */
}

void FD_CLR(int fd, fd_set *set) {
	if (0 <= fd && fd < FD_SETSIZE) {
		*set = *set & ~(1<<fd);
	}
}

int FD_ISSET(int fd, fd_set *set) {
	return 0 <= fd && fd < FD_SETSIZE && (*set & (1 << fd));
}

void FD_SET(int fd, fd_set *set) {
	if (0 <= fd && fd < FD_SETSIZE) {
		*set = *set | (1<<fd);
	}
}

void FD_ZERO(fd_set *set) {
	*set = 0;
}