Fusion:Vector

A vector is a collection of pointers, known as elements. It’s like an array, except that the elements are kept packed together so that all indices from 0 to one less than the count of elements are populated. When an element is added it gets the next free index, and when an element is removed all the following elements are shifted down to fill the hole.

The vector uses shared memory to hold its elements, so it’s usable by any fusionee. That means you’ll often want to use shared memory yourself for the data that the element pointers refer to. Elements cannot be NULL pointers.

You create a vector with fusion_vector_init, at which point you specify an initial capacity of how many elements you expect to keep in it. Don’t initialize a vector twice as that will lead to a memory leak of the capacity allocated the first time.

When you’re all done call fusion_vector_destroy to free up the memory used to hold the elements. If the elements themselves need to be freed up, be sure to do that before destroying the vector unless you have some other way of getting back their pointers than through the vector.

To quickly determine if there are any elements in the vector, use fusion_vector_has_elements or its inverse fusion_vector_is_empty. On the other hand, if you need to know just how many elements are in the vector, call fusion_vector_size.

To put an element into the vector, you first have to allocate whatever it points to since the vector just holds the pointer for you. You add it to the end of the vector with the next free with fusion_vector_add. You can also insert an element at a particular index with fusion_vector_insert which will push up all existing elements to make a hole at the desired index and then store the new element there. You must not insert an element to have an index higher than the current count of elements (i.e. you can’t force a hole in the vector).

You can change the index of an element with fusion_element_move. Just like inserting, you must not create a hole by moving beyond the end of the vector.

To take an element out of the vector, pass its index to fusion_vector_remove. If you want to use a vector like a stack, you might want to use fusion_vector_remove_last and not bother with the indices at all.

If you need to know the index of an element (which you somehow already have the pointer of), use fusion_vector_index_of. Or, if you just want to know whether it’s already in the vector use fusion_vector_contains, which you might need to do before adding an element to the vector since there’s nothing preventing the same pointer being stored as two different elements.

To get a specific element by index, fusion_vector_at will do the trick. But, you’ll more likely want to iterate all elements in the vector with either the fusion_vector_foreach or the fusion_vector_foreach_reverse macro.