/*
 * 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 <poliqarp-config.h>

#include <assert.h>
#include <stdlib.h>

#include <bp/common.h>
#include "block-list.h"

struct free_block_list_elem {
   size_t block;
   struct free_block_list_elem *next;
};

void free_block_list_create(struct free_block_list *list, FILE *file,
   size_t block_size, struct vector *map)
{
   list->file = file;
   list->block_size = block_size;
   list->head = NULL;
   list->map = map;
}

void free_block_list_destroy(struct free_block_list *list)
{
   while (list->head) {
      struct free_block_list_elem *this = list->head;
      list->head = list->head->next;
      free(this);
   }
}

void free_block_list_append(struct free_block_list *list, size_t block)
{
   struct free_block_list_elem *elem = bp_malloc(sizeof *elem);
   elem->next = list->head;
   elem->block = block;
   list->head = elem;
}

static size_t free_block_list_try_alloc(struct free_block_list *list)
{
   if (list->head) {
      struct free_block_list_elem *this = list->head;
      size_t res;
      list->head = list->head->next;
      res = this->block;
      free(this);
      return res;
   } else {
      return -1;
   }
}

static void free_block_list_create_block(struct free_block_list *list)
{
   fseeko(list->file, 0, SEEK_END);
   free_block_list_append(list, ftello(list->file) / list->block_size);
}

size_t free_block_list_alloc(struct free_block_list *list)
{
   size_t res = free_block_list_try_alloc(list);
   if (res == (size_t)-1) {
      free_block_list_create_block(list);
      res = free_block_list_try_alloc(list);
      assert(res != (size_t)-1);
   }
   vector_append(list->map, res);
   return res;
}

