Also ignore .git directories
[metastore.git] / utils.c
blobf7eb194b568a80f034b8379e9f8f55eedb0d3e66
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <ctype.h>
4 #include <string.h>
5 #include <stdint.h>
7 #include "utils.h"
8 #include "metastore.h"
10 void *
11 xmalloc(size_t size)
13 void *result = malloc(size);
14 if (!result) {
15 fprintf(stderr, "Failed to malloc %zi bytes\n", size);
16 exit(EXIT_FAILURE);
18 return result;
21 char *
22 xstrdup(const char *s)
24 char *result = strdup(s);
25 if (!result) {
26 fprintf(stderr, "Failed to strdup %zi bytes\n", strlen(s));
27 exit(EXIT_FAILURE);
29 return result;
32 void
33 binary_print(const char *s, ssize_t len)
35 ssize_t i;
37 for (i = 0; i < len; i++) {
38 if (isprint(s[i]))
39 printf("%c", s[i]);
40 else
41 printf("0x%02X", (int)s[i]);
45 void
46 xfwrite(const void *ptr, size_t size, FILE *stream)
48 if (fwrite(ptr, size, 1, stream) != 1) {
49 perror("fwrite");
50 exit(EXIT_FAILURE);
54 void
55 write_int(uint64_t value, size_t len, FILE *to)
57 char buf[len];
58 int i;
60 for (i = 0; i < len; i++)
61 buf[i] = ((value >> (8 * i)) & 0xff);
62 xfwrite(buf, len, to);
65 void
66 write_binary_string(const char *string, size_t len, FILE *to)
68 xfwrite(string, len, to);
71 void
72 write_string(const char *string, FILE *to)
74 xfwrite(string, strlen(string) + 1, to);
77 uint64_t
78 read_int(char **from, size_t len, const char *max)
80 uint64_t result = 0;
81 int i;
83 if (*from + len > max) {
84 fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
85 exit(EXIT_FAILURE);
88 for (i = 0; i < len; i++)
89 result += (((*from)[i] & 0xff) << (8 * i));
90 *from += len;
91 return result;
94 char *
95 read_binary_string(char **from, size_t len, const char *max)
97 char *result;
99 if (*from + len > max) {
100 fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
101 exit(EXIT_FAILURE);
104 result = xmalloc(len);
105 strncpy(result, *from, len);
106 *from += len;
107 return result;
110 char *
111 read_string(char **from, const char *max)
113 return read_binary_string(from, strlen(*from) + 1, max);