New command: kick-job.
[beanstalkd.git] / ms.c
blob7480707358978ab466b991b57579854a7d2f3b42
1 #include <stdint.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include "dat.h"
6 void
7 ms_init(ms a, ms_event_fn oninsert, ms_event_fn onremove)
9 a->used = a->cap = a->last = 0;
10 a->items = NULL;
11 a->oninsert = oninsert;
12 a->onremove = onremove;
15 static void
16 grow(ms a)
18 void **nitems;
19 size_t ncap = (a->cap << 1) ? : 1;
21 nitems = malloc(ncap * sizeof(void *));
22 if (!nitems) return;
24 memcpy(nitems, a->items, a->used * sizeof(void *));
25 free(a->items);
26 a->items = nitems;
27 a->cap = ncap;
30 int
31 ms_append(ms a, void *item)
33 if (a->used >= a->cap) grow(a);
34 if (a->used >= a->cap) return 0;
36 a->items[a->used++] = item;
37 if (a->oninsert) a->oninsert(a, item, a->used - 1);
38 return 1;
41 static int
42 ms_delete(ms a, size_t i)
44 void *item;
46 if (i >= a->used) return 0;
47 item = a->items[i];
48 a->items[i] = a->items[--a->used];
50 /* it has already been removed now */
51 if (a->onremove) a->onremove(a, item, i);
52 return 1;
55 void
56 ms_clear(ms a)
58 while (ms_delete(a, 0));
59 free(a->items);
60 ms_init(a, a->oninsert, a->onremove);
63 int
64 ms_remove(ms a, void *item)
66 size_t i;
68 for (i = 0; i < a->used; i++) {
69 if (a->items[i] == item) return ms_delete(a, i);
71 return 0;
74 int
75 ms_contains(ms a, void *item)
77 size_t i;
79 for (i = 0; i < a->used; i++) {
80 if (a->items[i] == item) return 1;
82 return 0;
85 void *
86 ms_take(ms a)
88 void *item;
90 if (!a->used) return NULL;
92 a->last = a->last % a->used;
93 item = a->items[a->last];
94 ms_delete(a, a->last);
95 ++a->last;
96 return item;