ajsecord / vector_t

A dynamic array of fixed-size objects for C

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

vector_t: A dynamic array for C

Build Status Code Coverage

vector_t is a dynamic array of fixed-size objects for C, similar to C++'s std::vector class. There are many like it, but this one is mine.

Runtime behavior

vector_t has the following runtime behavior:

  • Element access takes O(1) operations
  • Appending N elements to a vector causes amortized O(N) allocations
  • Memory usage can be controlled using either vector_reserve() or vector_size_to_fit().

Compilation environment

Except for the optional vector_convenience_accessors.h macros, vector_t only requires a C99 compiler and has no external dependencies. Clang and GCC are specifically tested.

Convenience accessors

Using the macros in vector_convenience_accessors.h requires the common C extensions of typeof() operator and statement expressions. These extensions are well-supported on GCC and clang, at least.

vector_t does not know anything about the types of objects stored as its elements, only the size of an element in bytes. Because of this, the library's interface is expressed in terms of void * pointers, which can lead to some cumbersome pointer casting to the correct type when accessing elements:

int value = *(int *)vector_get(vector, index);

Several convenience macros are defined in vector_convenience_accessors.h to help reduce the verbosity:

int value = VECTOR_GET(vector, index, int);

Similarly, setting the value of an element requires a temporary value on the stack:

int value = 1;
vector_set(vector, index, &value);

Using the convenience macros, this is simplified to:

VECTOR_SET(vector, index, 1);

Controlling how the library interacts with the system

As an advanced option, it is possible to control how the library interacts with the system. For example, the user can replace the memory allocator used by providing their own implementation of realloc() or how the library should react to catastrophic problems by providing their own implementation of abort(). See vector_system.h for more information.

About

A dynamic array of fixed-size objects for C

License:Apache License 2.0


Languages

Language:C 74.5%Language:C++ 24.3%Language:Makefile 1.2%