25 wassertrv(size
> 0, NULL
);
27 bag
= wmalloc(sizeof(WMBag
));
29 bag
->items
= wmalloc(sizeof(void*) * size
);
39 WMGetBagItemCount(WMBag
*bag
)
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
,
53 sizeof(void*) * appendedBag
->count
);
55 bag
->count
+= appendedBag
->count
;
56 bag
->size
+= appendedBag
->count
;
62 WMPutInBag(WMBag
*bag
, void *item
)
64 WMInsertInBag(bag
, bag
->count
, item
);
70 WMInsertInBag(WMBag
*bag
, int index
, void *item
)
72 if (bag
->count
== bag
->size
) {
74 bag
->items
= wrealloc(bag
->items
, sizeof(void*) * bag
->size
);
77 if (index
>= 0 && index
< bag
->count
) {
78 memmove(&bag
->items
[index
+1], &bag
->items
[index
],
79 (bag
->count
- index
) * sizeof(void*));
81 /* If index is invalid, place it at end */
84 bag
->items
[index
] = item
;
90 WMGetFirstInBag(WMBag
*bag
, void *item
)
94 for (i
= 0; i
< bag
->count
; i
++) {
95 if (bag
->items
[i
] == item
) {
104 WMGetLastInBag(WMBag
*bag
, void *item
)
108 for (i
= bag
->count
-1; i
>= 0; i
--) {
109 if (bag
->items
[i
] == item
) {
118 WMRemoveFromBag(WMBag
*bag
, void *item
)
122 i
= WMGetFirstInBag(bag
, item
);
124 WMDeleteFromBag(bag
, i
);
131 WMDeleteFromBag(WMBag
*bag
, int index
)
133 wassertr(index
>= 0 && index
< bag
->count
);
135 if (index
< bag
->count
-1) {
136 memmove(&bag
->items
[index
], &bag
->items
[index
+ 1],
137 (bag
->count
- index
- 1) * sizeof(void*));
144 WMGetFromBag(WMBag
*bag
, int index
)
146 wassertrv(index
>= 0 && index
< bag
->count
, NULL
);
148 return bag
->items
[index
];
153 WMCountInBag(WMBag
*bag
, void *item
)
157 for (j
= 0, i
= 0; j
< bag
->count
; j
++) {
158 if (bag
->items
[j
] == item
)
167 WMSortBag(WMBag
*bag
, int (*comparer
)(const void*, const void*))
169 qsort(bag
->items
, bag
->count
, sizeof(void*), comparer
);
175 WMFreeBag(WMBag
*bag
)
183 WMEmptyBag(WMBag
*bag
)
191 WMMapBag(WMBag
*bag
, void *(*function
)(void *))
194 WMBag
*new = WMCreateBag(bag
->size
);
196 for (i
= 0; i
< bag
->count
; i
++) {
197 WMPutInBag(new, (*function
)(bag
->items
[i
]));
205 WMReplaceInBag(WMBag
*bag
, int index
, void *item
)
209 wassertrv(index
>= 0 && index
< bag
->count
, NULL
);
211 old
= bag
->items
[index
];
213 bag
->items
[index
] = item
;