-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
66 lines (52 loc) · 1.35 KB
/
util.c
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
/* See LICENSE file for copyright and license details. */
#include "util.h"
// like calloc, but with error throwing
void* ecalloc(size_t nmemb, size_t size) {
void* p;
if (!(p = calloc(nmemb, size)))
die("calloc:");
return p;
}
// throw an error and die
void die(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
exit(1);
}
// throw a message and die w/ success 🗿
void die_happy(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
fputc('\n', stdout);
exit(0);
}
// count number of ones in binary representation
unsigned int n_ones(unsigned int n) {
unsigned int c = 0;
while (n) {
c += n & 1;
n >>= 1;
}
return c;
}
int cmpint(const void* p1, const void* p2) {
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp(3) arguments are "pointers
to char", hence the following cast plus dereference */
return *((int*)p1) > *(int*)p2;
}
unsigned int intersect(int x1, int y1, unsigned w1, unsigned h1, int x2, int y2,
unsigned w2, unsigned h2) {
return MAX(0, MIN(x1 + w1, x2 + w2) - MAX(x1, x2))
* MAX(0, MIN(y1 + h1, y2 + h2) - MAX(y1, y2));
}