Skip to content

Commit

Permalink
Array-to-vector function added.
Browse files Browse the repository at this point in the history
This constructs a vector from an array, either through copying or through
simply taking ownership of the passed pointer.
  • Loading branch information
lycantrophe committed May 16, 2013
1 parent 600d704 commit 9ebdd62
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
15 changes: 15 additions & 0 deletions vector.c
Expand Up @@ -41,6 +41,21 @@ void push( struct Vector* V, void* item ) {
++V->size;
}

struct Vector* atov( void* array, size_t alloced, size_t typesize, unsigned int size ) {
return atovown( memcpy( malloc( alloced ), array, typesize * size ),
alloced, typesize, size );
}

struct Vector* atovown( void* array, size_t alloced, size_t typesize, unsigned int size ) {
Vector* V = malloc( sizeof( struct Vector ) );
V->size = size;
V->item_size = typesize;
V->capacity = alloced;
V->base = array;

return V;
}

void* at( struct Vector* V, unsigned int index ) {
assert( index <= V->size );
return (char*)V->base + ( V->item_size * index );
Expand Down
12 changes: 12 additions & 0 deletions vector.h
Expand Up @@ -15,6 +15,18 @@ typedef struct Vector Vector;
*/
extern struct Vector* vector( size_t typesize, unsigned int icap );

/*
* Creates a vector from an array. Requires exact vector size (alloc'd area),
* element size (sizeof) and number of elements, counting from 0.
*/
extern struct Vector* atov( void* array, size_t alloced, size_t typesize, unsigned int size );

/*
* Works exactly like atov, but takes ownership of the passed array and uses it
* for its underlying data. Avoids copying.
*/
extern struct Vector* atovown( void* array, size_t alloced, size_t typesize, unsigned int size );

/*
* Insert an element at the back of the vector. Copies the void* content
*/
Expand Down

0 comments on commit 9ebdd62

Please sign in to comment.