Skip to content

Commit

Permalink
Add cvector_swap() (#57)
Browse files Browse the repository at this point in the history
* Add cvector_swap()

* Fix type comparision in vector_swap test
  • Loading branch information
RobLoach authored Oct 31, 2023
1 parent 0573629 commit d6cb7c2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
16 changes: 16 additions & 0 deletions cvector.h
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,22 @@ typedef struct cvector_metadata_t {
} \
} while (0)

/**
* @brief cvector_swap - exchanges the content of the vector by the content of another vector of the same type
* @param vec - the original vector
* @param other - the other vector to swap content with
* @param type - the type of both vectors
* @return void
*/
#define cvector_swap(vec, other, type) \
do { \
if (vec && other) { \
cvector_vector_type(type) cv_swap__ = vec; \
vec = other; \
other = cv_swap__; \
} \
} while (0)

/**
* @brief cvector_set_capacity - For internal use, sets the capacity variable of the vector
* @param vec - the vector
Expand Down
27 changes: 27 additions & 0 deletions unit-tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,33 @@ UTEST(test, vector_copy) {
cvector_free(b);
}

UTEST(test, vector_swap) {
cvector_vector_type(int) a = NULL;
cvector_vector_type(int) b = NULL;

cvector_push_back(a, 1);
cvector_push_back(a, 2);
cvector_push_back(a, 3);

cvector_push_back(b, 4);
cvector_push_back(b, 5);
cvector_push_back(b, 6);
cvector_push_back(b, 7);

ASSERT_EQ(cvector_size(a), (size_t)3);
ASSERT_EQ(cvector_size(b), (size_t)4);

cvector_swap(a, b, int);

ASSERT_EQ(cvector_size(a), (size_t)4);
ASSERT_EQ(cvector_size(b), (size_t)3);

ASSERT_EQ(a[0], 4);
ASSERT_EQ(a[1], 5);
ASSERT_EQ(b[0], 1);
ASSERT_EQ(b[1], 2);
}

UTEST(test, vector_reserve) {
int i;
cvector_vector_type(int) c = NULL;
Expand Down

0 comments on commit d6cb7c2

Please sign in to comment.