-
Notifications
You must be signed in to change notification settings - Fork 0
Cookbook
Pablo R. edited this page Oct 6, 2025
·
1 revision
Practical compositions that show how STRAP building blocks fit together in real-world scenarios.
Process arbitrarily large log files without per-line allocations by reusing strap_line_buffer_read()
:
#include "strap.h"
#include <stdio.h>
static void analyse_log(FILE *fp)
{
strap_line_buffer_t buf;
strap_line_buffer_init(&buf);
size_t line_no = 0;
char *line;
while ((line = strap_line_buffer_read(fp, &buf)) != NULL)
{
++line_no;
size_t tokens_count = 0;
char **tokens = strsplit_limit(line, " ", 3, &tokens_count);
if (!tokens)
continue; /* propagate error via strap_last_error() if needed */
if (tokens_count >= 3)
printf("#%zu %s [%s] %s\n", line_no, tokens[0], tokens[1], tokens[2]);
strsplit_free(tokens);
}
strap_line_buffer_free(&buf);
}
Turn CSV rows into typed fields using predicate-based splitting:
#include "strap.h"
#include <stdio.h>
static bool is_csv_delim(unsigned char ch, void *userdata)
{
(void)userdata;
return ch == ',' || ch == '\n' || ch == '\r';
}
void print_csv_columns(const char *row)
{
size_t count = 0;
char **cols = strsplit_predicate(row, is_csv_delim, NULL, 0, &count);
if (!cols)
return;
for (size_t i = 0; i < count; ++i)
printf("col[%zu] = '%s'\n", i, cols[i]);
strsplit_free(cols);
}
Emit human-readable timestamps in the host timezone by combining the portable timezone shims:
#include "strap.h"
#include <stdio.h>
void print_local_timestamp(void)
{
struct timeval now = { time(NULL), 0 };
char iso[64];
if (strap_time_format_iso8601_local(now, iso, sizeof(iso)) == 0)
printf("Local time: %s\n", iso);
else
fprintf(stderr, "Failed to format time: %s\n",
strap_error_string(strap_last_error()));
}
Compose strreplace()
with the SIMD-enabled join helpers to quickly render miniature templates:
#include "strap.h"
#include <stdio.h>
char *render_message(const char *user, const char *status)
{
const char *parts[] = {"Hello ", user, ", status: ", status};
char *base = strjoin(parts, 4, "");
if (!base)
return NULL;
char *clean = strreplace(base, "\n", " ");
free(base);
return clean;
}
These snippets are intentionally small so they can be copied into new codebases. Adapt them to your allocation strategy (arena/heap) and error-reporting needs.