Last active
November 27, 2023 16:46
-
-
Save pervognsen/fed0b1328b10b63f51ad42f961fc4058 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import libc {...} | |
struct StrLinesIter { | |
next: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_lines(str: char const*): StrLinesIter { | |
return {next = str}; | |
} | |
func str_lines_next(iter: StrLinesIter*): bool { | |
if (!*iter.next) { | |
return false; | |
} | |
iter.start = iter.next; | |
iter.end = iter.next; | |
while (*iter.end && *iter.end != '\n') { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
struct StrWordsIter { | |
next: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_words(str: char const*): StrWordsIter { | |
return {next = str}; | |
} | |
func str_words_next(iter: StrWordsIter*): bool { | |
iter.start = iter.next; | |
while (isspace(*iter.start)) { | |
iter.start++; | |
} | |
if (!*iter.start) { | |
return false; | |
} | |
iter.end = iter.start; | |
while (*iter.end && !isspace(*iter.end)) { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
struct StrTokensIter { | |
next: char const*; | |
delims: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_tokens(str: char const*, delims: char const*): StrTokensIter { | |
return {next = str, delims = delims}; | |
} | |
func str_contains(str: char const*, c: char): bool { | |
while (*str) { | |
if (*str == c) { | |
return true; | |
} | |
str++; | |
} | |
return false; | |
} | |
func str_tokens_next(iter: StrTokensIter*): bool { | |
iter.start = iter.next; | |
while (str_contains(iter.delims, *iter.start)) { | |
iter.start++; | |
} | |
if (!*iter.start) { | |
return false; | |
} | |
iter.end = iter.start; | |
while (*iter.end && !str_contains(iter.delims, *iter.end)) { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
func main(argc: int, argv: char**): int { | |
str := " first\n\n \nsecond\nthird"; | |
for (it := str_lines(str); str_lines_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
str = " first second\r third\n\t fourth "; | |
for (it := str_words(str); str_words_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
for (it := str_tokens(str, " \t\n\r"); str_tokens_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment