options/posix: Fix strtok_r()
+#include <bits/ensure.h>
#include <stdlib.h>
#include <string.h>
-#include <bits/ensure.h>
+#include <frigg/debug.hpp>
char *strdup(const char *string) {
auto num_bytes = strlen(string);
@@ -44,19 +45,34 @@ size_t strnlen(const char *s, size_t n) {
char *strtok_r(char *__restrict s, const char *__restrict del, char **__restrict m) {
__ensure(m);
- // Skip initial delimiters.
- char *w = s ? s : *m;
- while(*w && strchr(del, *w))
- w++;
+ // We use *m = null to memorize that the entire string was consumed.
+ char *tok;
+ if(s) {
+ tok = s;
+ }else if(*m) {
+ tok = *m;
+ }else {
+ return nullptr;
+ }
- *m = w;
+ // Skip initial delimiters.
+ // After this loop: *tok is non-null iff we return a token.
+ while(*tok && strchr(del, *tok))
+ tok++;
// Replace the following delimiter by a null-terminator.
- while(*w && !strchr(del, *w))
- w++;
- *w = 0;
-
- return *m;
+ // After this loop: *p is null iff we reached the end of the string.
+ auto p = tok;
+ while(*p && !strchr(del, *p))
+ p++;
+
+ if(*p) {
+ *p = 0;
+ *m = p + 1;
+ }else{
+ *m = nullptr;
+ }
+ return tok;
}
char *strsep(char **stringp, const char *delim) {
