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


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

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

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

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

		printf("  |");

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

		printf("|\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;
}