#include #include #include "array.h" array * array_new() { struct array * v; v = (struct array *) malloc( sizeof( struct array ) ); v->capacity = ARRAY_INIT_CAPACITY; v->total = 0; v->items = malloc(sizeof(void *) * v->capacity); return v; } int array_length(array *v) { return v->total; } char * array_join( struct array * parts, char * separator ) { int count = array_length( parts ); char * fullText = ""; for (int i = 0; i < count; ++i) { char * currentPart = array_get( parts, i ); fullText = text_concatenate( fullText, currentPart ); if( i < count-1 ) { fullText = text_concatenate( fullText, separator ); } printf("join: %s\n", fullText); //fullText = text_concatenate( fullText, separator ); } return fullText; } static void array_resize( array *v, int capacity ) { #ifdef DEBUG_ON printf("array_resize: %d to %d\n", v->capacity, capacity); #endif void **items = realloc( v->items, sizeof( void * ) * capacity ); //if (items) { v->items = items; v->capacity = capacity; //} } void array_add( array * v, void * item ) { if ( v->capacity == v->total ){ array_resize( v, v->capacity * 2 ); } v->items[v->total++] = item; } void array_set( array * v, int index, void * item ) { if (index >= 0 && index < v->total){ v->items[index] = item; } } void * array_get( array *v, int index ) { if ( index >= 0 && index < v->total ){ return v->items[index]; } return NULL; } int array_push( array * v, void * item ) { array_add( v, item ); return v->total; } void array_unshift( array * v, void * item ) { int length = v->total; v->total++; if ( v->capacity == v->total ){ array_resize( v, v->capacity * 2 ); } for ( int i = length - 1; i >= 0; --i ) { v->items[ i + 1 ] = v->items[ i ]; } v->items[ 0 ] = item; } void array_delete( array * v, int index) { if ( index < 0 || index >= v->total ){ return; } v->items[index] = NULL; for ( int i = index; i < v->total - 1; i++ ) { v->items[i] = v->items[i + 1]; v->items[i + 1] = NULL; } v->total--; if ( v->total > 0 && v->total == v->capacity / 4 ){ array_resize( v, v->capacity / 2 ); } } void * array_pop( array * v ) { int count = array_length( v ); void * item = array_get( v, count - 1 ); array_delete( v, count - 1 ); return item; } void array_free(array *v) { free( v->items ); }