aboutsummaryrefslogtreecommitdiffstats
path: root/darray.c
blob: 4df4064834ae06588af89249e42d7429d9f20f81 (plain) (blame)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include "darray.h"

#include "debug.h"

DArray::DArray(size_t data_size, size_t init_size)
{
	int i;

	if (init_size <= 0)
	{
		goto error;
	}

	this->_max = init_size;
	this->data = (void **)malloc(init_size*sizeof(void *));
	this->end = 0;
	//this->size = data_size;
	this->_expand = DEFAULT_EXPAND_RATE;


error:;
}

DArray::~DArray()
{

}

int DArray::push(void *val)
{
	if (this->data[this->end] != NULL)
	{
		ENL();
	}

	this->data[this->end] = val;
	this->end++;

	if (this->end > this->_max)
	{
		return this->expand();
	}

	return 0;
}

int DArray::expand()
{
	size_t old_max = this->_max;

	if (this->resize(this->_max + DEFAULT_EXPAND_RATE))
	{
		goto error;
	}

	memset(this->data + old_max, 0, this->_expand+1);
	return 0;

error:
	ENL();
	return -1;
}

int DArray::resize(size_t size)
{
	int i = 0;
	void *data = NULL;

	if (size < 1)
	{
		ENL();
		goto error;
	}

	if (size < this->_max)
	{
		i = this->_max;
		do 
		{
			if (this->data[i-1] != NULL)
			{
				free(this->data[i-1]);//??? is there is some data then free it?
				this->data[i-1] = NULL;
			}
			i -= 1;
		} while (i-1 == size);
	}
	this->_max = size;

	data = (void **)realloc(this->data, this->_max * sizeof(void*));
	if (data == NULL)
	{
		ENL();
		goto error;
	}

	this->data = (void **)data;
	return 0;

error:
	ERROR("\n");
	return -1;
}

int DArray::set(int idx, void *val)
{
	if (idx > this->_max)
	{
		ENL();
		return -1;
	}

	if (idx>this->end)
	{
		this->end = idx;
	}

	this->data[idx] = val;

	return 0;
}

void* DArray::get(int idx)
{
	if (idx<0)
	{
		return NULL;
	}

	if (idx>=this->end)
	{
		return NULL; //???
	}

	return this->data[idx];
}

int DArray::count()
{
	return this->end;
}