50
SMap * s_map_new ( CompFunc comp_func, FuncPointer free_key,
51
FuncPointer free_value) {
52
SMap * s_map_new (CompFunc comp_func,
53
HashFunc key_hash_func,
55
FuncPointer free_value) {
52
56
SMap * self = malloc (sizeof (SMap));
53
57
SMapClass * klass = malloc (sizeof (SMapClass));
58
62
klass->is_equal = comp_func;
60
64
/* free_* functions need to be checked if they are null and set the pointer
61
* to free or s_base_object_free ()... Have to decite which...
65
* to free or s_base_object_free ()... Have to decide which...?
63
67
klass->free_key = free_key;
64
68
klass->free_value = free_value;
70
/* if no func is set we have to use some other metod of
72
if (key_hash_func == NULL){
73
klass->key_hash_func = s_hash_object;
75
klass->key_hash_func = key_hash_func;
78
/* We do our own freeing of objects. */
79
self->priv->array = s_dynamic_array_new (S_MAP_DEFAULT_NUMBER_OF_BUCKETS,
78
void s_map_add (SMap * self ,void * key, void * value) {
79
SMapItem ** items = self->priv->items;
94
void s_map_add (SMap * self, spointer key, spointer value) {
95
SDynamicArray * array = self->priv->array;
80
96
SMapItem * item = s_map_item_new (key, value);
98
/* We have to generate a key to use as an index in the DynamicArray. */
99
HashFunc hash_func = self->klass->key_hash_func;
100
hash_t hash = hash_func (key);
101
/* We need to mod it with the max size of the array. */
102
hash = hash % S_MAP_DEFAULT_NUMBER_OF_BUCKETS;
81
104
if (self->priv->len == 0) {
82
items = realloc (items, sizeof(SMapItem));
105
/* Since we know that there are no items in the array we can skip the
106
* check if the new place is taken. and just and an array to it.
108
SDynamicArray * bucket = s_dynamic_array_new (8, NULL);
109
s_dynamic_array_set (array, hash, bucket);
110
s_dynamic_array_set (bucket, 0, item);
86
items = realloc (items, sizeof(SMapItem) * (self->priv->len + 1));
87
items[self->priv->len-1] = item;
113
/* Figure out if the bucket exists. */
114
SDynamicArray * bucket = NULL;
115
if (s_dynamic_array_get (array, hash) == NULL) {
116
bucket = s_dynamic_array_new (8, NULL);
118
/* We get the bucket */
119
bucket = S_DYNAMIC_ARRAY(s_dynamic_array_get (array, hash));
121
size_t bucket_len = s_dynamic_array_last_item (bucket);
122
s_dynamic_array_set (bucket, bucket_len, item);
92
126
void * s_map_get (SMap * self, void * key) {
93
SMapItem ** items = self->priv->items;
94
CompFunc comp_func = self->klass->is_equal;
95
for (size_t i = 0; i < self->priv->len; i++) {
96
sboolean is_item = comp_func (key, items[i]);