
#include "actconfig.h"
#include "actcomdef.h"
#include "actstdlib.h"

#include "acttestvector.h"
#include "acttestvector_private.h"


ITestVec *  
ITestVec_New(int initial_capacity)
{
    ITestVec * pMe = (ITestVec *) act_malloc(sizeof(ITestVec));
    
    if(pMe)
    {
        pMe->size = 0;
        pMe->capa = 0;
        pMe->body = (ITest**)malloc(sizeof(ITest*)*initial_capacity);
        if ( pMe->body ) 
        {
            pMe->capa = initial_capacity;
        }
    }
    return pMe;
}

void
ITestVec_Delete(ITestVec* pMe) 
{
    ITestVec_clear(pMe);
    act_free(pMe);
}

void
ITestVec_clear(ITestVec* pMe) 
{
    int i;
    for ( i = 0; i < pMe->size; ++i ) 
    {
        ITest_Delete(pMe->body[i]);
    }
    pMe->size = 0;
}


static void
ITestVec_grow(ITestVec* pMe) 
{
    if ( pMe->size >= pMe->capa ) 
    {
        int new_capa = pMe->capa + 8;
        ITest** new_body = (ITest**)malloc(sizeof(ITest*) * new_capa);
        if ( new_body ) 
        {
            int i;
            for ( i = 0; i < pMe->size; ++i ) 
            {
                new_body[i] = pMe->body[i];
            }
            act_free(pMe->body);
            pMe->body = new_body;
            pMe->capa = new_capa;
        }
    }
}

void
ITestVec_push_back(ITestVec* pMe, ITest* str)
{
    ITestVec_grow(pMe);
    pMe->body[pMe->size++] = str; //strdup(str);
}

void
ITestVec_insert_before(ITestVec* pMe, int pos, ITest* str) {
    int i;
    if ( pos < 0 ) return;
    if ( pos >= pMe->size ) return;
    ITestVec_grow(pMe);
    for ( i = pMe->size; i > pos; --i ) 
    {
        pMe->body[i] = pMe->body[i-1];
    }
    pMe->body[pos] = str; // strdup(str);
    ++pMe->size;
}

int
ITestVec_size(const ITestVec* pMe) 
{
    return pMe->size;
}

void
ITestVec_erase(ITestVec* pMe, int pos) 
{
    int i;
    
    if ( pos < 0 ) return;
    if ( pos >= pMe->size ) return;
    
    ITest_Delete(pMe->body[pos]);

    for ( i = pos; i < pMe->size - 1; ++i ) 
    {
        pMe->body[i] = pMe->body[i+1];
    }
    --pMe->size;
}

int
ITestVec_capacity(const ITestVec* pMe) 
{
    return pMe->capa;
}

const
ITest* ITestVec_get(const ITestVec* pMe, int index) 
{
    if ( index >= 0 || index < pMe->size ) 
    {
        return pMe->body[index];
    }
    return 0;
}

int
ITestVec_find(const ITestVec* pMe, /*const*/ ITest* pTest) 
{
    int i;
    for ( i = 0; i < pMe->size; ++i ) 
    {
        if ( strcmp((const char*)ITest_name(pTest), (const char*)ITest_name(pMe->body[i])) == 0 ) 
            return i;
    }
    return -1;
}
