1 //========================================================================
2 //
3 // GList.cc
4 //
5 // Copyright 2001-2003 Glyph & Cog, LLC
6 //
7 //========================================================================
8 
9 #include <aconf.h>
10 
11 #ifdef USE_GCC_PRAGMAS
12 #pragma implementation
13 #endif
14 
15 #include <stdlib.h>
16 #include <string.h>
17 #include "gmem.h"
18 #include "GList.h"
19 
20 //------------------------------------------------------------------------
21 // GList
22 //------------------------------------------------------------------------
23 
GList()24 GList::GList() {
25   size = 8;
26   data = (void **)gmallocn(size, sizeof(void*));
27   length = 0;
28   inc = 0;
29 }
30 
GList(int sizeA)31 GList::GList(int sizeA) {
32   size = sizeA ? sizeA : 8;
33   data = (void **)gmallocn(size, sizeof(void*));
34   length = 0;
35   inc = 0;
36 }
37 
~GList()38 GList::~GList() {
39   gfree(data);
40 }
41 
copy()42 GList *GList::copy() {
43   GList *ret;
44 
45   ret = new GList(length);
46   ret->length = length;
47   memcpy(ret->data, data, length * sizeof(void *));
48   ret->inc = inc;
49   return ret;
50 }
51 
append(void * p)52 void GList::append(void *p) {
53   if (length >= size) {
54     expand();
55   }
56   data[length++] = p;
57 }
58 
append(GList * list)59 void GList::append(GList *list) {
60   int i;
61 
62   while (length + list->length > size) {
63     expand();
64   }
65   for (i = 0; i < list->length; ++i) {
66     data[length++] = list->data[i];
67   }
68 }
69 
insert(int i,void * p)70 void GList::insert(int i, void *p) {
71   if (length >= size) {
72     expand();
73   }
74   if (i < 0) {
75     i = 0;
76   }
77   if (i < length) {
78     memmove(data+i+1, data+i, (length - i) * sizeof(void *));
79   }
80   data[i] = p;
81   ++length;
82 }
83 
del(int i)84 void *GList::del(int i) {
85   void *p;
86 
87   p = data[i];
88   if (i < length - 1) {
89     memmove(data+i, data+i+1, (length - i - 1) * sizeof(void *));
90   }
91   --length;
92   if (size - length >= ((inc > 0) ? inc : size/2)) {
93     shrink();
94   }
95   return p;
96 }
97 
sort(int (* cmp)(const void * obj1,const void * obj2))98 void GList::sort(int (*cmp)(const void *obj1, const void *obj2)) {
99   qsort(data, length, sizeof(void *), cmp);
100 }
101 
reverse()102 void GList::reverse() {
103   void *t;
104   int n, i;
105 
106   n = length / 2;
107   for (i = 0; i < n; ++i) {
108     t = data[i];
109     data[i] = data[length - 1 - i];
110     data[length - 1 - i] = t;
111   }
112 }
113 
expand()114 void GList::expand() {
115   size += (inc > 0) ? inc : size;
116   data = (void **)greallocn(data, size, sizeof(void*));
117 }
118 
shrink()119 void GList::shrink() {
120   size -= (inc > 0) ? inc : size/2;
121   data = (void **)greallocn(data, size, sizeof(void*));
122 }
123