42 lines
1.2 KiB
C
42 lines
1.2 KiB
C
|
|
// log_once_box.h - Simple one-shot logging helpers (Box)
|
||
|
|
// Provides: lightweight, thread-safe "log once" primitives for stderr/write
|
||
|
|
// Used by: guard boxes that need single notification without spamming
|
||
|
|
#ifndef HAKMEM_LOG_ONCE_BOX_H
|
||
|
|
#define HAKMEM_LOG_ONCE_BOX_H
|
||
|
|
|
||
|
|
#include <stdatomic.h>
|
||
|
|
#include <stdbool.h>
|
||
|
|
#include <stddef.h>
|
||
|
|
#include <stdio.h>
|
||
|
|
#include <unistd.h>
|
||
|
|
#include <stdarg.h>
|
||
|
|
|
||
|
|
typedef struct {
|
||
|
|
_Atomic int logged;
|
||
|
|
} hak_log_once_t;
|
||
|
|
|
||
|
|
#define HAK_LOG_ONCE_INIT {0}
|
||
|
|
|
||
|
|
static inline bool hak_log_once_should_log(hak_log_once_t* flag, bool quiet) {
|
||
|
|
if (quiet) return false;
|
||
|
|
if (!flag) return true;
|
||
|
|
return atomic_exchange_explicit(&flag->logged, 1, memory_order_relaxed) == 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
static inline void hak_log_once_write(hak_log_once_t* flag, bool quiet, int fd, const char* buf, size_t len) {
|
||
|
|
if (!buf) return;
|
||
|
|
if (!hak_log_once_should_log(flag, quiet)) return;
|
||
|
|
(void)write(fd, buf, len);
|
||
|
|
}
|
||
|
|
|
||
|
|
static inline void hak_log_once_fprintf(hak_log_once_t* flag, bool quiet, FILE* stream, const char* fmt, ...) {
|
||
|
|
if (!stream || !fmt) return;
|
||
|
|
if (!hak_log_once_should_log(flag, quiet)) return;
|
||
|
|
va_list ap;
|
||
|
|
va_start(ap, fmt);
|
||
|
|
(void)vfprintf(stream, fmt, ap);
|
||
|
|
va_end(ap);
|
||
|
|
}
|
||
|
|
|
||
|
|
#endif // HAKMEM_LOG_ONCE_BOX_H
|