Split meta entry functions into a separate file
[metastore.git] / utils.c
blob91cb1edb0bdf9a3fcca376c7c34ec3ceafb4ae00
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <ctype.h>
4 #include <string.h>
5 #include <stdint.h>
6 #include <stdarg.h>
8 #include "utils.h"
10 int verbosity = 0;
12 int
13 msg(int level, const char *fmt, ...)
15 int ret;
16 va_list ap;
18 if (level > verbosity)
19 return 0;
21 va_start(ap, fmt);
22 ret = vfprintf(stderr, fmt, ap);
23 va_end(ap);
24 return ret;
27 void *
28 xmalloc(size_t size)
30 void *result = malloc(size);
31 if (!result) {
32 fprintf(stderr, "Failed to malloc %zi bytes\n", size);
33 exit(EXIT_FAILURE);
35 return result;
38 char *
39 xstrdup(const char *s)
41 char *result = strdup(s);
42 if (!result) {
43 fprintf(stderr, "Failed to strdup %zi bytes\n", strlen(s));
44 exit(EXIT_FAILURE);
46 return result;
49 void
50 binary_print(const char *s, ssize_t len)
52 ssize_t i;
54 for (i = 0; i < len; i++) {
55 if (isprint(s[i]))
56 printf("%c", s[i]);
57 else
58 printf("0x%02X", (int)s[i]);
62 void
63 xfwrite(const void *ptr, size_t size, FILE *stream)
65 if (fwrite(ptr, size, 1, stream) != 1) {
66 perror("fwrite");
67 exit(EXIT_FAILURE);
71 void
72 write_int(uint64_t value, size_t len, FILE *to)
74 char buf[len];
75 int i;
77 for (i = 0; i < len; i++)
78 buf[i] = ((value >> (8 * i)) & 0xff);
79 xfwrite(buf, len, to);
82 void
83 write_binary_string(const char *string, size_t len, FILE *to)
85 xfwrite(string, len, to);
88 void
89 write_string(const char *string, FILE *to)
91 xfwrite(string, strlen(string) + 1, to);
94 uint64_t
95 read_int(char **from, size_t len, const char *max)
97 uint64_t result = 0;
98 int i;
100 if (*from + len > max) {
101 fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
102 exit(EXIT_FAILURE);
105 for (i = 0; i < len; i++)
106 result += (((*from)[i] & 0xff) << (8 * i));
107 *from += len;
108 return result;
111 char *
112 read_binary_string(char **from, size_t len, const char *max)
114 char *result;
116 if (*from + len > max) {
117 fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
118 exit(EXIT_FAILURE);
121 result = xmalloc(len);
122 strncpy(result, *from, len);
123 *from += len;
124 return result;
127 char *
128 read_string(char **from, const char *max)
130 return read_binary_string(from, strlen(*from) + 1, max);