How to add element(int64 key and as_map value) to as_map?


#1

Something like as_intmap_set_map(p_map, 12 , p_value)?


#2

as_map has a generic key, value function, which can take any type

int as_hashmap_set(as_hashmap * map, const as_val * key, const as_val * val);


#3

Code below:

static inline int as_int64map_set_int64(as_map * m, int64_t k, int64_t v)

{

 return as_util_hook(set, 1, m, (as_val *) as_integer_new(k), (as_val *) as_integer_new(v));

}

static inline int64_t as_int64map_get_int64(as_map * m, int64_t k)

{

 as_integer key;

 as_val * v = as_util_hook(get, NULL, m, (as_val *) as_integer_init(&key, k));

 as_integer * i = as_integer_fromval(v);

 return i ? as_integer_toint(i) : 0;

}


#4

The added helper functions are good. Alternatively, using existing API:

// Setting an integer
as_map_set(m, (as_val *) as_integer_new(1), (as_val *) as_integer_new(10000));

// Getting an integer
as_integer_init(&key, 1);
as_integer_get((as_integer *)as_map_get(m, (as_val *)&key)));

#5

Thanks for your reply.


#6

Do I assume correctly that if this example is used as-is, it would result in memory leak, since as_integer_new allocates an as_integer on heap, and it must be then freed with as_integer_destroy, which is missing from this example? And if so, it would also mean that in order to be able to call as_integer_destroy, you HAVE to store the as_integer (or a pointer to it) in some variable (like the “key” above). Is this correct?


#7

as_hashmap takes ownership of keys/values and destroys them when the entry is removed. There will be no memory leak if the hashmap itself is eventually destroyed.