Files

55 lines
1.3 KiB
C
Raw Permalink Normal View History

2026-05-24 23:24:25 -07:00
#include "util.h"
2026-05-25 17:25:50 -07:00
#include <errno.h>
2026-05-24 23:24:25 -07:00
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2026-05-25 17:25:50 -07:00
#include <time.h>
2026-05-24 23:24:25 -07:00
2026-05-25 23:13:27 -07:00
void *realloc_safe(void *oldptr, size_t size) {
2026-05-25 17:25:50 -07:00
static const char OOM_MSG[] = "fatal: out of memory\n";
2026-05-25 23:13:27 -07:00
void *ptr = realloc(oldptr, size);
2026-05-25 17:25:50 -07:00
if (size && !ptr) {
fwrite(OOM_MSG, 1, sizeof(OOM_MSG) - 1, stderr);
abort();
2026-05-24 23:24:25 -07:00
}
2026-05-25 17:25:50 -07:00
return ptr;
2026-05-24 23:24:25 -07:00
}
2026-05-25 23:13:27 -07:00
void *malloc_safe(size_t size) {
2026-05-25 17:25:50 -07:00
return realloc_safe(NULL, size);
}
// asprintf is not POSIX
2026-05-25 23:13:27 -07:00
int alloc_sprintf(char *restrict *restrict out, const char *restrict fmt, ...) {
2026-05-25 17:25:50 -07:00
va_list args;
va_start(args, fmt);
va_list args2;
va_copy(args2, args);
int need = vsnprintf(NULL, 0, fmt, args2);
va_end(args2);
*out = realloc_safe(*out, need + 1);
int written = vsnprintf(*out, need + 1, fmt, args);
va_end(args);
return written;
}
2026-05-25 23:13:27 -07:00
void log_error(const char *restrict fmt, ...) {
2026-05-25 17:25:50 -07:00
time_t cur_time = time(NULL);
struct tm tm;
localtime_r(&cur_time, &tm);
char time_str[32];
strftime(time_str, sizeof(time_str), "%c", &tm);
fprintf(stderr, "[%s] error: ", time_str);
2026-05-24 23:24:25 -07:00
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fputc('\n', stderr);
}
2026-05-25 17:25:50 -07:00
2026-05-25 23:13:27 -07:00
void log_errno(const char *detail) {
2026-05-25 17:25:50 -07:00
log_error("%s: %s", detail, strerror(errno));
}