summaryrefslogtreecommitdiff
path: root/utils.c
blob: f7eb194b568a80f034b8379e9f8f55eedb0d3e66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdint.h>

#include "utils.h"
#include "metastore.h"

void *
xmalloc(size_t size)
{
        void *result = malloc(size);
        if (!result) {
                fprintf(stderr, "Failed to malloc %zi bytes\n", size);
                exit(EXIT_FAILURE);
        }
        return result;
}

char *
xstrdup(const char *s)
{
	char *result = strdup(s);
	if (!result) {
		fprintf(stderr, "Failed to strdup %zi bytes\n", strlen(s));
		exit(EXIT_FAILURE);
	}
	return result;
}

void
binary_print(const char *s, ssize_t len)
{
	ssize_t i;

	for (i = 0; i < len; i++) {
		if (isprint(s[i]))
			printf("%c", s[i]);
		else
			printf("0x%02X", (int)s[i]);
	}
}

void
xfwrite(const void *ptr, size_t size, FILE *stream)
{
	if (fwrite(ptr, size, 1, stream) != 1) {
		perror("fwrite");
		exit(EXIT_FAILURE);
	}
}

void
write_int(uint64_t value, size_t len, FILE *to)
{
	char buf[len];
	int i;

	for (i = 0; i < len; i++)
		buf[i] = ((value >> (8 * i)) & 0xff);
	xfwrite(buf, len, to);
}

void
write_binary_string(const char *string, size_t len, FILE *to)
{
	xfwrite(string, len, to);
}

void
write_string(const char *string, FILE *to)
{
	xfwrite(string, strlen(string) + 1, to);
}

uint64_t
read_int(char **from, size_t len, const char *max)
{
	uint64_t result = 0;
	int i;

	if (*from + len > max) {
		fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < len; i++)
		result += (((*from)[i] & 0xff) << (8 * i));
	*from += len;
	return result;
}

char *
read_binary_string(char **from, size_t len, const char *max)
{
	char *result;

	if (*from + len > max) {
		fprintf(stderr, "Attempt to read beyond end of file, corrupt file?\n");
		exit(EXIT_FAILURE);
	}

	result = xmalloc(len);
	strncpy(result, *from, len);
	*from += len;
	return result;
}

char *
read_string(char **from, const char *max)
{
	return read_binary_string(from, strlen(*from) + 1, max);
}