/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2004-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

#include <stdlib.h>
#include <string.h>

#include <bp/common.h>
#include "vector.h"

void vector_create(struct vector *v, int options)
{
   v->size = 32;
   v->used = 0;
   v->data = bp_malloc(v->size * sizeof *v->data);
   v->options = options;
   if (v->options & VECTOR_ZERO)
      memset(v->data, 0, v->size * sizeof *v->data);
}

static void vector_size_assert(struct vector *v, size_t which)
{
   size_t oldsize = v->size;
   while (v->size <= which)
      v->size *= 2;
   if (v->size != oldsize) {
      v->data = bp_realloc(v->data, v->size * sizeof *v->data);
      if (v->options & VECTOR_ZERO)
         memset(v->data + oldsize, 0, (v->size - oldsize) * sizeof *v->data);
   }
   if (v->used < which + 1)
      v->used = which + 1;
}

void vector_destroy(struct vector *v)
{
   free(v->data);
}

void vector_append(struct vector *v, uint32_t val)
{
   vector_set(v, v->used, val);
}

uint32_t vector_get(const struct vector *v, size_t x)
{
   return v->data[x];
}

void vector_set(struct vector *v, size_t i, uint32_t val)
{
   vector_size_assert(v, i);
   v->data[i] = val;
}

void vector_inc(struct vector *v, size_t i)
{
   vector_size_assert(v, i);
   v->data[i]++;
}

size_t vector_length(const struct vector *v)
{
   return v->used;
}

