sv_splitlines
I'm hoping the title gives it away, but if not, see corresponding test for usage.
Notes on this commit:
- line endings "\r\n" and "\n" are handled
String_Viewsis a dynamic array of itemsString_View, following typical nob dynamic array conventions- splitlines implies not including the line endings (as opposed to something like readlines which would)
Instead of returning a dynamic array that will need to be freed, what about something along the lines of nob_da_foreach:
#define NOBDEF static inline
#define NOB_STRIP_PREFIX
#define NOB_IMPLEMENTATION
#include "nob.h"
NOBDEF Nob_String_View nob_sv_splitline(Nob_String_View *sv) {
Nob_String_View line = sv_chop_by_delim(sv, '\n');
if (line.count && line.data[line.count - 1] == '\r')
line.count--;
return line;
}
// Nob_String_View *sv, Nob_String_View line
#define nob_sv_split_by_line(sv, line) \
for (Nob_String_View (line) = nob_sv_splitline((sv)); (sv)->count || (line).count; (line) = nob_sv_splitline((sv)))
int main(void) {
int result = 0;
String_Builder sb = {};
if (!read_entire_file(__FILE__, &sb))
return_defer(1);
String_View sv = sb_to_sv(sb);
nob_sv_split_by_line(&sv, sv2) {
nob_log(INFO, "\"" SV_Fmt "\"", SV_Arg(sv2)); //
}
defer:
sb_free(sb);
return result;
}
First of all, thanks for taking the time to have a well thought out suggestion.
If common lexing tasks would benefit from having the data/count info around for a bit, then having a String_Views might outweigh the cost of having heap allocated memory. Though, your point is not lost on me, and the simplicity of a macro may be a better approach.
How about only adding sv_split_line, and leaving it up to the user to make their own dynamic array or macro depending on the use-case?