vector: add a reference iterator foreach loop

For storage of types larger than native types a ref based iterated loop
is handy to avoid copy.
This commit is contained in:
Alaric Senat 2023-07-05 10:28:52 +02:00 committed by Steve Lhomme
parent 5344b0a910
commit 314391afe6
2 changed files with 24 additions and 1 deletions

View File

@ -665,7 +665,21 @@ vlc_vector_move_(char *array, size_t index, size_t count, size_t target)
++vlc_vector_idx_##item)
/**
* Returns a reference to the vector's first element.
* For-each loop with a reference iterator.
*
* Should be used for vector holding non-trivially copyable data.
*
* \param[out] ref The reference iterator
* \param[in] pv a pointer to the vector
*/
#define vlc_vector_foreach_ref(ref, pv) \
for (size_t vlc_vector_idx_##ref = 0; \
vlc_vector_idx_##ref < (pv)->size && \
((ref) = &(pv)->data[vlc_vector_idx_##ref], true); \
++vlc_vector_idx_##ref)
/**
* Returns the vector's last element.
*/
#define vlc_vector_last(pv) \
( \

View File

@ -257,6 +257,15 @@ static void test_vector_foreach(void)
}
assert(count == 10);
count = 0;
const int *ref;
vlc_vector_foreach_ref(ref, &vec)
{
assert(*ref == count);
assert(ref == &vec.data[count]);
count++;
}
vlc_vector_destroy(&vec);
}