MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
07_lines.c

One Str owns a whole novel, and views walk its 22,750 lines without a single further allocation.

/* Together: one Str owns the file, views walk its lines. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen("data/pg2554.txt", "rb");
if (f == NULL) {
perror("data/pg2554.txt");
return EXIT_FAILURE;
}
Str text = { 0 };
bool ok = str_append_file(&text, f);
fclose(f);
if (!ok) return EXIT_FAILURE;
size_t lines = 0, chapters = 0, mentions = 0;
StrView rest = str_view(&text);
StrView line;
while (sv_split_next(&rest, SV("\n"), &line)) {
line = sv_trim(line); /* the file uses \r\n; trim drops the \r */
lines++;
if (sv_starts_with(line, SV("Author:"))) {
printf("%.*s\n", STR_FMT(line));
}
if (sv_starts_with(line, SV("CHAPTER "))) chapters++;
/* Count every occurrence in the line by sliding past each match. */
StrView scan = line;
size_t at;
while ((at = sv_find(scan, SV("Raskolnikov"))) != SV_NPOS) {
mentions++;
scan = sv_slice(scan, at + 1, scan.len);
}
}
printf("%zu lines, %zu chapters, %zu mentions of Raskolnikov\n", lines,
chapters, mentions);
str_free(&text); /* every view into it dies here */
return EXIT_SUCCESS;
}
size_t len
Number of bytes in the view.
Definition str.h:74
size_t sv_find(StrView v, StrView needle)
Index of the first needle in v.
Definition str.c:237
#define SV(lit)
View of a string literal, with its length computed at compile time.
Definition str.h:80
StrView str_view(const Str *s)
Borrow the whole of s.
Definition str.c:212
#define STR_FMT(s)
printf helper: printf("%.*s", STR_FMT(s)) prints exactly len bytes.
Definition str.h:85
#define SV_NPOS
Returned by the find functions when there is no match.
Definition str.h:217
void str_free(Str *s)
Free the buffer and reset s to the zero state.
Definition str.c:50
bool str_append_file(Str *s, FILE *f)
Append everything left to read from f.
Definition str.c:156
StrView sv_trim(StrView v)
v without leading and trailing ASCII whitespace: space, \t, \n, \v, \f and \r.
Definition str.c:279
bool sv_starts_with(StrView v, StrView prefix)
True when v begins with prefix.
Definition str.c:259
bool sv_split_next(StrView *rest, StrView sep, StrView *piece)
Cut the piece before sep off rest.
Definition str.c:286
StrView sv_slice(StrView v, size_t from, size_t to)
Bytes from up to but not including to.
Definition str.c:268
Owned, growable byte string.
Definition str.h:64
Non-owning view of bytes; handy for passing slices and literals around.
Definition str.h:72