]> jfr.im git - irc/quakenet/newserv.git/blame - lib/array.c
r592@blue (orig r482): cruicky | 2006-05-04 15:00:58 +0100
[irc/quakenet/newserv.git] / lib / array.c
CommitLineData
c86edd1d
Q
1/*
2Operservice 2 - array.c
3Arrays are used all over in O2. This .c supplies some functions for handling
4them.
5(C) Michael Meier 2000-2001 - released under GPL
6-----------------------------------------------------------------------------
7This program is free software; you can redistribute it and/or
8modify it under the terms of the GNU General Public License
9as published by the Free Software Foundation; either version 2
10of the License, or (at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with this program; if not, write to the Free Software
19Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20------------------------------------------------------------------------------
21*/
22
23#include <stdio.h>
24#include <stdlib.h>
25#include "array.h"
26#include "../core/error.h"
27
28#ifndef ARLIM1
29#define ARLIM1 100 /* If new memory is needed for an array, this many */
30 /* records will be allocated. */
31#endif
32#ifndef ARLIM2
33#define ARLIM2 150 /* If more than this number of records are free in an */
34 /* array, memory is freed. */
35#endif
36
37void array_init(array *a, unsigned int memberlen) {
38 a->cursi=0;
39 a->maxsi=0;
40 a->memberlen=memberlen;
41 a->content=NULL;
42 a->arlim1=ARLIM1;
43 a->arlim2=ARLIM2;
44}
45
46void array_setlim1(array *a, unsigned int lim) {
47 a->arlim1=lim;
48}
49
50void array_setlim2(array *a, unsigned int lim) {
51 a->arlim2=lim;
52}
53
54int array_getfreeslot(array *a) {
55 if ((a->cursi+1)>=a->maxsi) {
56 /* Reallocation needed */
57 a->maxsi+=a->arlim1;
58 a->content=realloc(a->content,a->maxsi*a->memberlen);
59 if (a->content==NULL) {
60 Error("array",ERR_FATAL,"Couldn't allocate memory for growing array");
61 exit(1);
62 }
63 }
64 a->cursi++;
65 return (a->cursi-1);
66}
67
68void array_delslot(array *a, int slotn) {
69 if (slotn >= a->cursi) { return; }
70 a->cursi--;
71 if (a->cursi!=slotn) {
72 memcpy(a->content + (slotn * a->memberlen), a->content + (a->cursi * a->memberlen),a->memberlen);
73 }
74 if ((a->cursi + a->arlim2) < a->maxsi) {
75 /* Let's free some memory */
76 a->maxsi = a->cursi + a->arlim1;
77 a->content=realloc(a->content,a->maxsi*a->memberlen);
78 if (a->content==NULL) {
79 Error("array",ERR_FATAL,"Couldn't allocate memory for shrinking array?!?");
80 exit(1);
81 }
82 }
83}
84
85void array_free(array *a) {
86 free(a->content);
87 a->cursi=0;
88 a->maxsi=0;
89 a->memberlen=0;
90 a->content=NULL;
91 a->arlim1=ARLIM1;
92 a->arlim2=ARLIM2;
93}