fixed many bugs, removed linked list
[wmaker-crm.git] / WINGs / bag.c
blobc15b527b6ba3724a0171d22ceb6e7325a5b040c5
3 #include <stdlib.h>
4 #include <string.h>
6 #include "WUtil.h"
10 struct W_Bag {
11 int size;
12 int count;
14 void **items;
20 WMBag*
21 WMCreateBag(int size)
23 WMBag *bag;
25 wassertrv(size > 0, NULL);
27 bag = wmalloc(sizeof(WMBag));
29 bag->items = wmalloc(sizeof(void*) * size);
30 bag->size = size;
31 bag->count = 0;
33 return bag;
38 int
39 WMGetBagItemCount(WMBag *bag)
41 return bag->count;
46 void
47 WMAppendBag(WMBag *bag, WMBag *appendedBag)
49 bag->items = wrealloc(bag->items,
50 sizeof(void*) * (bag->size+appendedBag->count));
52 memcpy(bag->items + bag->count, appendedBag->items, appendedBag->count);
54 bag->count += appendedBag->count;
59 void
60 WMPutInBag(WMBag *bag, void *item)
62 WMInsertInBag(bag, bag->count, item);
67 void
68 WMInsertInBag(WMBag *bag, int index, void *item)
70 if (bag->count == bag->size) {
71 bag->size += 16;
72 bag->items = wrealloc(bag->items, sizeof(void*) * bag->size);
75 bag->items[bag->count++] = item;
79 int
80 WMGetFirstInBag(WMBag *bag, void *item)
82 int i;
84 for (i = 0; i < bag->count; i++) {
85 if (bag->items[i] == item) {
86 return i;
89 return -1;
93 int
94 WMGetLastInBag(WMBag *bag, void *item)
96 int i;
98 for (i = bag->count-1; i>= 0; i--) {
99 if (bag->items[i] == item) {
100 return i;
103 return -1;
107 void
108 WMRemoveFromBag(WMBag *bag, void *item)
110 int i;
112 i = WMGetFirstInBag(bag, item);
113 if (i >= 0) {
114 WMDeleteFromBag(bag, i);
120 void
121 WMDeleteFromBag(WMBag *bag, int index)
123 if (index < 0 || index >= bag->count)
124 return;
126 if (index < bag->count-1) {
127 memmove(&bag->items[index], &bag->items[index + 1],
128 (bag->count - index - 1) * sizeof(void*));
130 bag->count--;
134 void*
135 WMGetFromBag(WMBag *bag, int index)
137 if (index < 0 || index >= bag->count) {
138 return NULL;
141 return bag->items[index];
146 WMCountInBag(WMBag *bag, void *item)
148 int i, j;
150 for (j = 0, i = 0; j < bag->count; j++) {
151 if (bag->items[j] == item)
152 i++;
154 return i;
159 void
160 WMSortBag(WMBag *bag, int (*comparer)(void*, void*))
162 qsort(bag->items, bag->count, sizeof(void*), comparer);
167 void
168 WMFreeBag(WMBag *bag)
170 free(bag->items);
171 free(bag);
175 void
176 WMEmptyBag(WMBag *bag)
178 bag->count = 0;
183 WMBag*
184 WMMapBag(WMBag *bag, void *(*function)(void *))
186 int i;
187 WMBag *new = WMCreateBag(bag->size);
189 for (i = 0; i < bag->count; i++) {
190 WMPutInBag(new, (*function)(bag->items[i]));
193 return new;