summaryrefslogtreecommitdiff
path: root/cycle.c
blob: 6bdf994181f2a050b07fd5839f3a9d8469deff62 (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
#include <stddef.h> // for size_t
#include <stdlib.h> // for malloc() and free()
#include <assert.h>
#include "utils.h"
#include "cycle.h"

/* cycling iterable */
struct Cycle {
	const void *base;
	size_t i;
	size_t memb_n;
	size_t memb_size;
};

/*
 * cycle_new: create a new cycle of array startinng at 'base' with memb_n
 * elements each of size 'memb_size'
 */
struct Cycle *
cycle_new(const void *base, size_t memb_n, size_t memb_size)
{
	assert(base != NULL);
	assert(memb_n > 0);
	assert(memb_size > 0);
	struct Cycle *cycle = malloc(sizeof *cycle);

	if (cycle == NULL) {
		return NULL;
	}
	cycle->base = base;
	cycle->i = 0;
	cycle->memb_n = memb_n;
	cycle->memb_size = memb_size;
	return cycle;
}

/* cycle_free: free memmory used by cycle */
void
cycle_free(struct Cycle *cycle)
{
	assert(cycle != NULL);
	free(cycle);
}

/* cycle_index: get index of current element of cycle */
size_t
cycle_index(struct Cycle *cycle)
{
	assert(cycle != NULL);
	return cycle->i;
}

/* cycle_current: get current element of cycle */
const void *
cycle_current(struct Cycle *cycle)
{
	assert(cycle != NULL);
	return (const char *)cycle->base + cycle->memb_size*cycle->i;
}

/* cycle_next: point cycle to next element and return it */
const void *
cycle_next(struct Cycle *cycle)
{
	assert(cycle != NULL);
	cycle->i = (cycle->i >= cycle->memb_n-1) ? 0 : cycle->i+1;
	return cycle_current(cycle);
}

/* cycle_prev: point cycle to previous elemetn and return it */
const void *
cycle_prev(struct Cycle *cycle)
{
	assert(cycle != NULL);
	cycle->i = (cycle->i <= 0) ? cycle->memb_n-1 : cycle->i-1;
	return cycle_current(cycle);
}