sync with latest
[sdk/emulator/qemu.git] / hw / yagl_vector.c
1 #include "yagl_vector.h"
2
3 #define YAGL_VECTOR_DEFAULT_CAPACITY 10
4
5 void yagl_vector_init(struct yagl_vector *v,
6                       int elem_size,
7                       int initial_capacity)
8 {
9     assert(elem_size > 0);
10
11     v->elem_size = elem_size;
12     v->capacity = (initial_capacity < YAGL_VECTOR_DEFAULT_CAPACITY) ?
13                       YAGL_VECTOR_DEFAULT_CAPACITY
14                     : initial_capacity;
15     v->data = g_malloc0(v->capacity * v->elem_size);
16     v->size = 0;
17 }
18
19 void yagl_vector_cleanup(struct yagl_vector *v)
20 {
21     g_free(v->data);
22     memset(v, 0, sizeof(*v));
23 }
24
25 void *yagl_vector_detach(struct yagl_vector *v)
26 {
27     void *tmp = v->data;
28     memset(v, 0, sizeof(*v));
29     return tmp;
30 }
31
32 int yagl_vector_size(struct yagl_vector *v)
33 {
34     return v->size;
35 }
36
37 int yagl_vector_capacity(struct yagl_vector *v)
38 {
39     return v->capacity;
40 }
41
42 void yagl_vector_push_back(struct yagl_vector *v, const void *elem)
43 {
44     if (v->size >= v->capacity) {
45         void *tmp;
46
47         v->capacity = (v->size * 3) / 2;
48
49         tmp = g_malloc(v->capacity * v->elem_size);
50         memcpy(tmp, v->data, (v->size * v->elem_size));
51
52         g_free(v->data);
53
54         v->data = tmp;
55     }
56
57     memcpy((char*)v->data + (v->size * v->elem_size), elem, v->elem_size);
58
59     ++v->size;
60 }
61
62 void yagl_vector_resize(struct yagl_vector *v, int new_size)
63 {
64     if (new_size <= v->capacity) {
65         v->size = new_size;
66     } else {
67         void *tmp;
68
69         v->capacity = (new_size * 3) / 2;
70
71         tmp = g_malloc(v->capacity * v->elem_size);
72         memcpy(tmp, v->data, (v->size * v->elem_size));
73
74         g_free(v->data);
75
76         v->data = tmp;
77         v->size = new_size;
78     }
79 }
80
81 void *yagl_vector_data(struct yagl_vector *v)
82 {
83     return v->data;
84 }