From 776276d5c7e67356a880f3e31076d32cdc1c1882 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 11:29:58 +0300 Subject: publish --- src/utils.h | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 src/utils.h (limited to 'src/utils.h') diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d8e7dda --- /dev/null +++ b/src/utils.h @@ -0,0 +1,95 @@ +// utils.h +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#include "string-view.h" + +#define NOP() do {} while (0) + +#define ARRAY_LENGTH(ARR) (sizeof (ARR)/sizeof (*(ARR))) + +#ifndef NDEBUG +#include +#define ASSERT assert +#else +#define ASSERT(...) NOP () +#endif + +#define UNUSED(EXP) ((void) EXP) + +#define FALLTHROUGH __attribute__ ((__fallthrough__)) + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) + +#ifndef NDEBUG +#define DEBUG(FMT, ...) \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ + __func__ __VA_OPT__ (,) __VA_ARGS__) +#else +#define DEBUG(...) NOP () +#endif + +#ifndef NDEBUG +#define ASSERT_MSG(EXP, FMT, ...) do if (!(EXP)) { \ + DEBUG (FMT __VA_OPT__ (,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) +#else +#define ASSERT_MSG(EXP, FMT, ...) NOP () +#endif + +#define MEASURE(FMT, ...) \ + for (struct timespec __ts0, __ts1, *__once = NULL; \ + clock_gettime (CLOCK_MONOTONIC, &__ts0), !__once; \ + clock_gettime (CLOCK_MONOTONIC, &__ts1), \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) \ + ": %s: " FMT " %.6fs\n", __func__, \ + __VA_ARGS__ __VA_OPT__ (,) \ + (__ts1.tv_sec - __ts0.tv_sec ) + \ + (__ts1.tv_nsec - __ts0.tv_nsec) / 1e9), \ + __once += 1) + +#define MIN(A, B) ((A) <= (B) ? (A) : (B)) + +struct timer_scope { + char *fmt; + struct timespec start; +}; + +static void +timer_end (struct timer_scope *t) +{ + struct timespec end; + clock_gettime (CLOCK_MONOTONIC, &end); + + double s = ((end.tv_sec - t->start.tv_sec) + + (end.tv_nsec - t->start.tv_nsec)/1e9); + + fprintf (stderr, t->fmt, s); + if (t->fmt[strlen (t->fmt) - 1] != ' ') + putc (' ', stderr); + fprintf (stderr, "took %.6fs\n", s); + free (t->fmt); +} + +#define MEASURE_SCOPE(FMT, ...) \ + __attribute__ ((cleanup (timer_end))) struct timer_scope __ts; \ + asprintf (&__ts.fmt, \ + __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT, \ + __func__ __VA_OPT__ (,) __VA_ARGS__); \ + clock_gettime (CLOCK_MONOTONIC, &__ts.start) + +struct string_view mmap_whole (int fd); +struct string_view mmap_n_from (int fd, size_t n, off_t offset); + +int asprintf (char **str, const char *fmt, ...); + +#endif // INCLUDED_UTILS_H +// utils.h ends here -- cgit v1.3.1