vector.h offers a robust and efficient way to create type-safe dynamic arrays in C. With its macro-based design, robust memory management, and comprehensive bounds checking, developers can easily implement custom vector types with zero dependencies. vector.h is portable and compatible across multiple compilers.
vector.h is a comprehensive macro-based library designed to create type-safe dynamic arrays in C. This library prioritizes robust functionality and offers extensive features that enhance productivity while coding in C.
To begin utilizing vector.h, follow these simple steps:
#include "vector.h"
VECTOR_DECLARE(MyVector, my_vector, float)
#include "my_vector.h"
VECTOR_DEFINE(MyVector, my_vector, float)
MyVector v = {0};
my_vector_push(&v, 3.14f);
my_vector_push(&v, 2.71f);
for (float *f = v.begin; f != v.end; f++) {
printf("%.2f ", *f);
}
my_vector_free(&v);
Alternatively, for single-file implementation:
#include "vector.h"
VECTOR_DECLARE(MyVector, my_vector, float)
VECTOR_DEFINE(MyVector, my_vector, float)
Here are some essential API functions offered by vector.h:
VECTOR_SIZE(vec) - Returns the number of elements in the vector.VECTOR_CAPACITY(vec) - Retrieves the total allocated capacity of the vector.vector_push(vec, value) - Appends an element to the vector in amortized O(1) time complexity.vector_pop(vec) - Removes and returns the last element from the vector.vector_get(vec, idx) / vector_set(vec, idx, value) - Provides random access to elements.vector_insert(vec, idx, value) / vector_delete(vec, idx) - Facilitates element insertion or removal at specified indices.vector_clear(vec) - Removes all elements from the vector.vector_free(vec) - Frees allocated memory for the vector.Before including the library, certain configurations can be defined:
#define VECTOR_NO_PANIC_ON_NULL 1 /* Suppresses panic on null pointer access */
#define VECTOR_NO_PANIC_ON_OOB 1 /* Prevents panic on out-of-bounds access */
#define VECTOR_REALLOC my_realloc /* Allows custom allocation function */
#define VECTOR_FREE my_free /* Allows custom deallocation function */
For testing the library functions, use CMake:
mkdir build
cmake -S . -B build/ -DCMAKE_BUILD_TYPE=Debug
cd build
make test
Tests include normal functionality, edge cases, memory allocation errors, and null pointer handling.
For developers and contributors interested in enhancing vector.h, it's advisable to start with vector.in.h, which includes hardcoded types and function names, and use libgen.py for generating the final library.
No comments yet.
Sign in to be the first to comment.