//
// Copyright (C) 2000-2002 Andrey Slepuhin <pooh@msu.ru>
//
// libp++ is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// libp++ is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libp++; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// $Source$
// $Revision$
// $Date$
// Author: Andrey Slepuhin <pooh@msu.ru>

#include "pxx_heap_allocator.ih"
#include "pxx_common.ih"

#include <new>
#include <string.h>

#ifndef WINDOWS
#include <unistd.h>
#include <sys/mman.h>
#endif

namespace pxx
{

size_t HeapAllocator::min_free_size ;

HeapAllocator::HeapAllocator (
  size_t _init_size /* = 0 */,      // Initial heap size, page size by default
  size_t const _max_size /* = 0 */, // Maximum size, not limited by default
  void* const _start /* = null */,
  int _fd /* = -1 */
) :
  Allocator (
    ALLOCATOR_HAS_GET_REAL_SIZE |
    ALLOCATOR_HAS_GET_BLOCK | ALLOCATOR_HAS_GET_BLOCK_WITH_SIZE
  ),
  Heap (_init_size, _max_size, _start, _fd)
{
  min_free_size = (1UL << get_order(sizeof(HeapAllocator::BlockHeader)));
  for (unsigned i = 0; i < sizeof(size_t) * 8; i++)
    lists[i].size = exps_of_two[i];
  BlockHeader* p = static_cast<BlockHeader*>(start_addr);
  (lists + get_order(current_size))->put(p);
}

HeapAllocator::~HeapAllocator () noexcept
{}

void* HeapAllocator::allocate (size_t _size)
{
  //
  // First try to allocate a block within current heap
  // Advance allocated size by number of bytes reserved for length
  _size += sizeof(uintptr_t);
  //
  // We cannot allocate less than minimal free size
  if (_size < min_free_size) _size = min_free_size ;
  //
  // Walk through apropriate block lists
  FreeBlockList* first = lists + get_order(_size);
  FreeBlockList* last = lists + cur_size_log;
  for (FreeBlockList* p = first; p <= last; p++) {
    //
    // Try to get free block from the list
    BlockHeader* q = p->get();
    //
    // Ok, we got one
    if (q != null) {
      while (p-- > first) {
        p->put(ptr_add_offset(q, p->size));
      }
      //
      // Set a size of allocated block
      q->set_size(first->size);
      //
      // And return shifted pointer
      return user_ptr(q);
    }
  }
  //
  // Here we did not find any non-empty free block list, or we want to
  // allocate too large amount of memory, so we should expand a heap
  {
    expand();
    // If heap consists of a single free block then expand it, otherwise
    // insert another one
    BlockHeader* p = last->get();
    if (p != null) {
      (last + 1)->put(p);
    } else {
      p = reinterpret_cast<BlockHeader*>(start_addr);
      last->put(ptr_add_offset(p, last->size));
    }
    //
    // Retry to allocate memory
    return HeapAllocator::allocate(_size - sizeof(uintptr_t));
  }
}

void HeapAllocator::deallocate (void* _ptr)
{
  BlockHeader* start = static_cast<BlockHeader*>(start_addr);
  //
  // Shift a pointer to a real start of memory block
  BlockHeader* p = true_ptr(_ptr);
  //
  // Get physical length of allocated block
  size_t size = p->get_size();
  //
  // Loop and glue adjacent free blocks
  for (; size < current_size; size <<= 1) {
    //
    // Get a pointer to appropriate adjacent block
    BlockHeader* q = ptr_add_offset(start, (ptr_sub(p, start) ^ size));
    //
    // If it is allocated or has wrong size
    if (size != q->size) break;
    //
    // Delete a block from free block list
    q->remove();
    //
    // Obtain a pointer to combined free block
    p = ptr_add_offset(start, ptr_sub(p, start) & ptr_sub(q, start));
  }
  //
  // Insert a block into appropriate free block list
  (lists + get_order(size))->put(p);
}

void* HeapAllocator::_reallocate (
  void* _ptr, size_t _size, size_t _oldsize
)
{
  void* p = HeapAllocator::allocate(_size - sizeof(uintptr_t));
  memcpy(p, _ptr, _oldsize - sizeof(uintptr_t));
  HeapAllocator::deallocate(_ptr);
  return p;
}

void* HeapAllocator::reallocate (void* _ptr, size_t _size)
{
  size_t oldsize;
  //
  // Shift a pointer to a real start of memory block
  BlockHeader* p = true_ptr(_ptr);
  //
  // Advance allocated size by number of bytes reserved for length
  _size += sizeof(uintptr_t);
  _size = exps_of_two[get_order(_size)];
  //
  // Get physical length of allocated block
  oldsize = p->get_size();
  if (_size > oldsize) {
    if ((ptr_sub(p, start_addr) & (_size - 1)) == 0) {
      size_t s = oldsize;
      while (s < _size) {
        if ((ptr_add_offset(p, s))->size != s)
        {
          return _reallocate(_ptr, _size, oldsize);
        } else {
          (ptr_add_offset(p, s))->remove();
          s <<= 1;
          p->set_size(s);
        }
      }
      return _ptr;
    } else {
      return _reallocate(_ptr, _size, oldsize);
    }
  } else if (_size < oldsize) {
    while (_size < oldsize) {
      oldsize >>= 1;
      (lists + get_order(oldsize))->put(ptr_add_offset(p, oldsize));
    }
    p->set_size(_size);
    return _ptr;
  } else {
    return _ptr;
  }
}

void HeapAllocator::memory_dump ()
{
  {
    BlockHeader* p = (BlockHeader*)(start_addr);
    printf("Heap at %p\n", p);
    do {
      if ((p->size & 0x01) != 0) {
        printf("a:%"PRIuPTR" ", p->get_size());
        p = ptr_add_offset(p, p->get_size());
      } else {
        printf("f:%"PRIuPTR" ", p->get_size());
        p = ptr_add_offset(p, p->get_size());
      }
    } while ((size_t)((char*)p - (char*)start_addr) < current_size);
    printf("\n\n");
  }
  {
    unsigned i;
    BlockHeader* p;
    for (i = get_order(min_free_size);
         i <= get_order(current_size);
         i++)
    {
      BlockHeader* q;
      printf("%4"PRIuPTR":", exps_of_two[i]);
      p = lists + i;
      q = p->next;
      if (q != p) {
        do {
          printf(" %p(%p,%p)", q, q->prev, q->next);
          q = q->next;
        } while (q != p);
      }
      printf("\n");
    }
    printf("\n");
  }
}

}
