vector icon indicating copy to clipboard operation
vector copied to clipboard

Safer Vector + VECTOR_ASSIGN_ARRAY

Open DBJDBJ opened this issue 5 years ago • 0 comments

Due to void * based design, currently one can add whatever one wants to this vector. double's to vector of int's , bool's or whatever. Core helper to avoid this might be this macro

#if defined( __clang__ ) || defined( __GNUC__ )
#define VECTOR_CHECK( V_ , E_ ) V_.element_size == sizeof(typeof(E_))
#endif

Now we can use it for example for safe array assign to the vector

// from chromium
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

// this might not fail on that many ocasions
#define VECTOR_ASSIGN_ARRAY(V_, S_, A_) \
do { \
assert( VECTOR_CHECK(V_, A_[0] ) ) ; \
for (int j = 0; j < S_ ; ++j) {\
	vector_push_back(&V_, &(A_[j]));\
};\
} while(0)

The usage

Vector vector;
// vector of int's
vector_setup(&vector, 10, sizeof(int));

int arr[] = { 1,2,3,4,5,6,7,8,9 };
VECTOR_ASSIGN_ARRAY(vector, COUNT_OF(arr), arr  );

printf("\n sum of: {");
int sum = 0;
VECTOR_FOR_EACH(&vector, iterator_ ) {
	sum += ITERATOR_GET_AS(int, &iterator_);
	printf(" %3d ", ITERATOR_GET_AS(int, &iterator_));
}
printf("} --> %d \n\n", sum );

If array element size and vector element size do not match VECTOR_CHECK will assert. Of course this is not type checking but mitigates the type mixing risk a little bit.

DBJDBJ avatar Sep 03 '20 06:09 DBJDBJ