MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
08_keep.c

Copy a view into a Str of its own when the text must outlive the buffer it came from.

/* Together: copy a view into its own Str when it must outlive its source. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
typedef struct Book {
Str title;
Str author;
} Book;
static void book_free(Book *b) {
str_free(&b->title);
str_free(&b->author);
}
/* Fill `b` from a Gutenberg header. Views in, owned copies out. */
static bool book_parse(Book *b, StrView text) {
StrView line;
while (sv_split_next(&text, SV("\n"), &line)) {
line = sv_trim(line);
if (sv_starts_with(line, SV("Title: "))) {
str_clear(&b->title);
if (!str_append(&b->title, sv_slice(line, 7, line.len)))
return false;
} else if (sv_starts_with(line, SV("Author: "))) {
str_clear(&b->author);
if (!str_append(&b->author, sv_slice(line, 8, line.len)))
return false;
}
}
return true;
}
int main(void) {
FILE *f = fopen("data/pg2554.txt", "rb");
if (f == NULL) return EXIT_FAILURE;
Str text = { 0 };
bool ok = str_append_file(&text, f);
fclose(f);
if (!ok) return EXIT_FAILURE;
Book book = { 0 };
ok = book_parse(&book, str_view(&text));
str_free(&text); /* the 1.2 MB buffer goes; the book keeps its copies */
if (!ok) {
book_free(&book);
return EXIT_FAILURE;
}
printf("%s by %s\n", str_cstr(&book.title), str_cstr(&book.author));
book_free(&book);
return EXIT_SUCCESS;
}
size_t len
Number of bytes in the view.
Definition str.h:74
const char * str_cstr(const Str *s)
NUL-terminated contents of s, for C APIs such as fopen and puts.
Definition str.c:216
#define SV(lit)
View of a string literal, with its length computed at compile time.
Definition str.h:80
void str_clear(Str *s)
Set the length to zero.
Definition str.c:71
StrView str_view(const Str *s)
Borrow the whole of s.
Definition str.c:212
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 str_append(Str *s, StrView v)
Append v.
Definition str.c:89
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