]> Pileus Git - ~andy/crypt/blob - util.c
Add some initial code
[~andy/crypt] / util.c
1 #include <stdint.h>
2 #include <stdarg.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 /* Log levels */
7 #define LOG_DEFAULT LOG_INFO
8
9 typedef enum {
10         LOG_DEBUG,
11         LOG_INFO,
12         LOG_WARN,
13         LOG_ERROR,
14 } log_t;
15
16 /* Globals */
17 int loglevel;
18
19 /* Helper functions */
20 static void message(int level, const char *prefix, const char *fmt, va_list ap)
21 {
22         if (level >= LOG_DEFAULT-loglevel) {
23                 fprintf(stderr, "%s: ", prefix);
24                 vfprintf(stderr, fmt, ap);
25                 fprintf(stderr, "\n");
26         }
27 }
28
29 /* Mesage functions */
30 void debug(const char *fmt, ...)
31 {
32         va_list ap;
33         va_start(ap, fmt);
34         message(LOG_DEBUG, "debug", fmt, ap);
35         va_end(ap);
36 }
37
38 void info(const char *fmt, ...)
39 {
40         va_list ap;
41         va_start(ap, fmt);
42         message(LOG_INFO, "info", fmt, ap);
43         va_end(ap);
44 }
45
46 void warn(const char *fmt, ...)
47 {
48         va_list ap;
49         va_start(ap, fmt);
50         message(LOG_WARN, "warning", fmt, ap);
51         va_end(ap);
52 }
53
54 void error(const char *fmt, ...)
55 {
56         va_list ap;
57         va_start(ap, fmt);
58         message(LOG_ERROR, "error", fmt, ap);
59         va_end(ap);
60         exit(1);
61 }
62
63 /* Hex dump */
64 void hexdump(const char *label, const char *prefix,
65                 const uint8_t *data, int len, ...)
66 {
67         va_list ap;
68         va_start(ap, len);
69
70         if (!label)   label  = "";
71         if (!prefix)  prefix = "%04x: ";
72
73         vprintf(label, ap);
74         for (int i = 0; i < len; i++) {
75                 if ((i % 16) == 0) {
76                         printf("\n");
77                         printf(prefix, i);
78                 } else if ((i % 8) == 0) {
79                         printf("  ");
80                 } else if ((i % 2) == 0) {
81                         printf(" ");
82                 }
83                 printf("%02hhx", data[i]);
84         }
85         printf("\n");
86
87         va_end(ap);
88 }
89
90
91 /* Misc */
92 void *alloc0(int size)
93 {
94         void *out = calloc(1, size);
95         if (!out)
96                 error("Alloc failed");
97         return out;
98 }