summaryrefslogtreecommitdiff
path: root/lib/libc/string/strtok_r.c
blob: e0cb4cacf107c2d9d76d7e5ee57850c6aad44618 (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
#include "stddef.h" // for NULL

#include <string.h> // for strchr, strtok_r

char *strtok_r(char *restrict s, const char *restrict sep, char **restrict state)
{
	if (s == NULL) {
		s = *state;
	}

	if (s == NULL) {
		return NULL;
	}

	while (*s && strchr(sep, *s)) {
		s++;
	}

	if (*s == '\0') {
		*state = NULL;
		return NULL;
	}

	char *start = s;

	while (*s && strchr(sep, *s) == NULL) {
		s++;
	}

	if (*s) {
		*s = '\0';
		*state = s + 1;
	} else {
		*state = NULL;
	}

	return start;
}