/*
 * We only support psVector's of type PS_TYPE_OTHER (i.e. (void *)) for now
 */
#include <assert.h>
#include "psLib.h"

psVector *
psVectorAlloc (int nalloc,		///< vector length 
	       psElemType type)		///< vector data type 
{
   assert (type == PS_TYPE_OTHER);

   psVector *vec = psAlloc(sizeof(psVector));
   vec->type.type = type;
   vec->type.dimen = PS_DIMEN_VECTOR;

   *(int *)&vec->n = *(int *)&vec->nalloc = nalloc;
   vec->data.V = psAlloc(nalloc*sizeof(void **));

   return vec;
}

void
psVectorFree(psVector *vec,
	     void (*elemFree)(void *))  ///< destructor for array data
	     
{
   if (psMemGetRefCounter(vec) != 1) {
      psMemDecrRefCounter(vec);
      return;
   }
   
   assert (vec->type.dimen == PS_DIMEN_VECTOR && vec->type.type == PS_TYPE_OTHER);

   if (elemFree != NULL && vec->nalloc > 0) {
      assert (vec->data.V != NULL);	/* choose any member of the union */
      const int n = vec->nalloc;
      for (int i = 0; i < n; i++) {
	 elemFree(vec->data.V[i]);
      }
   }

   psFree(vec->data.V);
   psFree(vec);
}
