MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
04_views.c

Trim, find and slice a StrView without allocating, and see why s is the wrong way to print one.

/* StrView on its own: inspect and slice text without allocating. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
StrView header = SV(" Title: Crime and Punishment\r\n");
StrView line = sv_trim(header);
printf("[%.*s]\n", STR_FMT(line));
if (sv_starts_with(line, SV("Title:"))) {
size_t colon = sv_find_byte(line, ':');
StrView key = sv_slice(line, 0, colon);
StrView value = sv_trim(sv_slice(line, colon + 1, line.len));
printf("key [%.*s] value [%.*s]\n", STR_FMT(key), STR_FMT(value));
/* Wrong: %s runs on to the next NUL, past the end of the view. */
printf("%%s on key prints [%s]\n", key.data);
}
size_t at = sv_find(line, SV("Punishment"));
if (at != SV_NPOS) printf("Punishment starts at byte %zu\n", at);
printf("ends with \"ment\": %d\n", sv_ends_with(line, SV("ment")));
/* argv strings already exist, so a view just borrows them. */
for (int i = 1; i < argc; i++) {
StrView arg = sv_from_cstr(argv[i]);
if (str_eq(arg, SV("--verbose"))) puts("verbose on");
}
return EXIT_SUCCESS;
}
size_t len
Number of bytes in the view.
Definition str.h:74
const char * data
First byte.
Definition str.h:73
size_t sv_find(StrView v, StrView needle)
Index of the first needle in v.
Definition str.c:237
StrView sv_from_cstr(const char *cstr)
View of cstr, measured with strlen.
Definition str.c:224
#define SV(lit)
View of a string literal, with its length computed at compile time.
Definition str.h:80
#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
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_ends_with(StrView v, StrView suffix)
True when v ends with suffix.
Definition str.c:263
bool sv_starts_with(StrView v, StrView prefix)
True when v begins with prefix.
Definition str.c:259
bool str_eq(StrView a, StrView b)
True when a and b hold the same bytes.
Definition str.c:220
StrView sv_slice(StrView v, size_t from, size_t to)
Bytes from up to but not including to.
Definition str.c:268
size_t sv_find_byte(StrView v, char c)
Index of the first c in v.
Definition str.c:231
Non-owning view of bytes; handy for passing slices and literals around.
Definition str.h:72