aboutsummaryrefslogtreecommitdiffstats
path: root/stack.c
blob: ded23776c8bea6d07ef8b13d9216e2dab7e34f59 (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
79
80
81
82
83
84
85
86
87
88
/*
 * stack.c
 * implementation of a generic stack
 *
 * Erik Liodden
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "structure.h"
#include "misc.h"

static void grow_stack(struct stack *s)
{
	s->alloc_length *= 2;
	s->elems = realloc(s->elems, s->alloc_length * s->elem_size);
	assert(s->elems != NULL);
}

void stack_init(struct stack *s, size_t elem_size, void (*freefn)(void *))
{
	s->elem_size = elem_size;
	s->log_length = 0;
	s->alloc_length = 4;
	s->elems = allocate(s->alloc_length * elem_size);
	s->freefn = freefn;
}

void stack_dispose(struct stack *s)
{
	int i;
	if (s->freefn) {
		for (i = 0; i < s->log_length; i++)
			s->freefn((char *)s->elems + (i * s->elem_size));
	}
	free(s->elems);
}

void stack_push(struct stack *s, void *elem_addr)
{
	if (s->log_length == s->alloc_length)
		grow_stack(s);
	void *target = (char *)s->elems + (s->log_length * s->elem_size);
	memcpy(target, elem_addr, s->elem_size);
	s->log_length++;
}

void stack_get(struct stack *s, void *elem_addr, int loc)
{
	if (s->log_length <= 0 || loc >= s->log_length || loc < 0) {
		fprintf(stderr, "array out of bounds: size %d, index: %d\n",
				s->log_length, loc);
		exit(EXIT_FAILURE);
	}
	void *source = (char *)s->elems + (loc * s->elem_size);
	memcpy(elem_addr, source, s->elem_size);
}

void stack_peek(struct stack *s, void *elem_addr)
{
	stack_get(s, elem_addr, s->log_length-1);
}

void stack_pop(struct stack *s, void *elem_addr)
{
	stack_peek(s, elem_addr);
	s->log_length--;
}

void stack_replace(struct stack *s, void *elem_addr, int loc)
{
	if (s->log_length > 0 && loc < s->log_length && loc >= 0) {
		fprintf(stderr, "array out of bounds: size %d, index: %d\n",
				s->log_length, loc);
		exit(EXIT_FAILURE);
	}
	if (s->freefn)
		s->freefn((char *)s->elems + (loc * s->elem_size));
	void *target = (char *)s->elems + (loc * s->elem_size);
	memcpy(target, elem_addr, s->elem_size);
}

int stack_length(struct stack *s)
{
	return s->log_length;
}