MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
06_sort.c

Sort an array of StrViews with qsort and sv_cmp().

/* StrView on its own: sort an array of views with qsort. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
static int cmp_views(const void *a, const void *b) {
return sv_cmp(*(const StrView *)a, *(const StrView *)b);
}
int main(void) {
StrView names[] = { SV("Sonya"), SV("Dunya"), SV("Razumikhin"),
SV("Raskolnikov"), SV("Porfiry") };
size_t n = sizeof names / sizeof names[0];
qsort(names, n, sizeof names[0], cmp_views);
for (size_t i = 0; i < n; i++) printf("%.*s\n", STR_FMT(names[i]));
return EXIT_SUCCESS;
}
#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
int sv_cmp(StrView a, StrView b)
Byte order like memcmp.
Definition str.c:252
Non-owning view of bytes; handy for passing slices and literals around.
Definition str.h:72