summaryrefslogtreecommitdiff
path: root/util.c
blob: 7bd9025a6653d8d42835ae48f65bd8cea00aa2d9 (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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <sys/time.h>
#include "util.h"


int uniqid(void) {
	static int i = 0;
	return i++;
}

void xxd(FILE *stream, const void *buf_, size_t length) {
	unsigned char *buf = (unsigned char*)buf_;

	for (size_t cursor = 0; cursor < length;) {
		fprintf(stream, "%08zx:", cursor);

		for (int i = 0; i < 16; i++) {
			if (i % 2 == 0) fprintf(stream, " ");
			if (i % 8 == 0) fprintf(stream, " ");
			if (cursor + i < length) fprintf(stream, "%02x", (unsigned)buf[cursor + i]);
			else fprintf(stream, "  ");
		}

		fprintf(stream, "  |");

		for (int i = 0; i < 16 && cursor + i < length; i++) {
			if (isprint(buf[cursor + i])) fprintf(stream, "%c", buf[cursor + i]);
			else fprintf(stream, ".");
		}

		fprintf(stream, "|\n");

		cursor += 16;
	}
}

ssize_t readall(int fd, void *data, size_t length) {
	size_t cursor = 0;
	while (cursor < length) {
		ssize_t nr = read(fd, data + cursor, length - cursor);
		if (nr < 0) {
			if (errno == EINTR) continue;
			return -1;
		}
		assert(nr > 0);
		cursor += nr;
	}
	return length;
}

ssize_t writeall(int fd, const void *data, size_t length) {
	size_t cursor = 0;
	while (cursor < length) {
		ssize_t nw = write(fd, data + cursor, length - cursor);
		if (nw < 0) {
			if (errno == EINTR) continue;
			return -1;
		}
		assert(nw > 0);
		cursor += nw;
	}
	return length;
}

int maxi(int a, int b) {
	return a > b ? a : b;
}

int64_t gettimestamp(void) {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec * 1000000LL + tv.tv_usec;
}