aboutsummaryrefslogtreecommitdiffstats
path: root/misc.c
blob: bc5a584f26df5b442097b04b88762584afb744e1 (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
/*
 * misc.c
 * decleration of various helper and misc functions
 *
 * Erik Liodden
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

/*
 * allocate `size` bytes and return a pointer to the allocated memory. if the
 * memory can't be allocated, the function will terminate the program.
 */
void *allocate(size_t size)
{
	void *result = malloc(size);
	if (result == NULL) {
		perror("unable to allocate memory");
		exit(EXIT_FAILURE);
	}
	return result;
}

/*
 * swap two pointers
 */
void swap(void *vp1, void *vp2, size_t elem_size)
{
	void *tmp = allocate(elem_size);
	memcpy(tmp, vp1, elem_size);
	memcpy(vp1, vp2, elem_size);
	memcpy(vp2, tmp, elem_size);
	free(tmp);
}

/*
 * rotate the first segment between `start` and `middle` after the remaining
 * part of the array
 */
void rotate(void *start, void *middle, void *end)
{
	int front = (char *)middle - (char *)start;
	int back = (char *)end - (char *)middle;
	char *buf = allocate(front);

	memcpy(buf, start, front);
	memmove(start, middle, back);
	memcpy((char *)start + back, buf, front);
}