nspkg / native_log.h
58 lines · 56 sloc · 2.27 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1/* printf/va_list stay in C so the line callback has the same ABI on each CPU. */
2#ifndef V_ALPM_NATIVE_LOG_H
3#define V_ALPM_NATIVE_LOG_H
4#include <stdint.h>
5#include <stdarg.h>
6#include <stdio.h>
7#include <stdlib.h>
8
9typedef void (*v_alpm_log_callback)(void *, uint32_t, const char *, va_list);
10typedef void (*v_alpm_log_line_callback)(void *, uint32_t, const char *);
11typedef struct v_alpm_log_line_state {
12 v_alpm_log_line_callback callback;
13 void *context;
14} v_alpm_log_line_state;
15
16static void v_alpm_log_line(void *context, uint32_t level, const char *format, va_list args) {
17 v_alpm_log_line_state *state = context;
18 if(!state || !state->callback || !format) { return; }
19 char buffer[4096];
20 va_list copy;
21 va_copy(copy, args);
22 int length = vsnprintf(buffer, sizeof(buffer), format, copy);
23 va_end(copy);
24 if(length < 0) { return; }
25 char *message = buffer;
26 if((size_t)length >= sizeof(buffer)) {
27 message = malloc((size_t)length + 1);
28 if(message) {
29 va_copy(copy, args);
30 vsnprintf(message, (size_t)length + 1, format, copy);
31 va_end(copy);
32 } else { message = buffer; }
33 }
34 state->callback(state->context, level, message);
35 if(message != buffer) { free(message); }
36}
37static void v_alpm_log_emit_format(v_alpm_log_callback callback, void *context, uint32_t level, const char *format, ...) {
38 va_list args;
39 va_start(args, format);
40 callback(context, level, format, args);
41 va_end(args);
42}
43static void v_alpm_log_emit(v_alpm_log_callback callback, void *context, uint32_t level, const char *message) {
44 if(callback) { v_alpm_log_emit_format(callback, context, level, "%s", message); }
45}
46static v_alpm_log_callback v_alpm_log_line_function(void) { return v_alpm_log_line; }
47static void *v_alpm_log_line_create(v_alpm_log_line_callback callback, void *context) {
48 v_alpm_log_line_state *state = malloc(sizeof(*state));
49 if(state) { state->callback = callback; state->context = context; }
50 return state;
51}
52static v_alpm_log_line_callback v_alpm_log_line_receiver(void *context) {
53 return context ? ((v_alpm_log_line_state *)context)->callback : NULL;
54}
55static void *v_alpm_log_line_context(void *context) {
56 return context ? ((v_alpm_log_line_state *)context)->context : NULL;
57}
58#endif
59