//
// 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>

#ifndef __pxx_chunk_allocator_block_header_hh__
#define __pxx_chunk_allocator_block_header_hh__

#include "pxx_common.hh"

namespace pxx
{

//
// Memory block header structure. It also contains fields and methods to keep
// all blocks in a balanced tree if memory allocator can not determine a start
// of the block containing a pointer.
class CABlockHeader
{
//
// All fields and methods are private because noone should use this class
// directly. Indeed it is better to have this class as inner class of
// ChunkAllocator<>, but this causes another instance of it in each template
// instantiation and makes notation worse readable.
private:
  template <typename type_t> friend class ChunkAllocator ;
  //
  // Reference counter that is equal to a number of allocated chunks in a
  // block
  uintptr_t ref_count ;
  //
  // Pointer to the previous free block
  CABlockHeader* prev ;
  //
  // Pointer to the next free block
  CABlockHeader* next ;
  //
  // Pointer to the left branch in the tree
  CABlockHeader* left ;
  //
  // Pointer to the right branch in the tree
  CABlockHeader* right ;
  //
  // A tree balance at the current node
  int balance ;
  //
  // Constructor
  CABlockHeader (CABlockHeader* _prev, CABlockHeader* _next) ;
  //
  NO_COPY_CTOR(CABlockHeader)
  NO_ASSIGN(CABlockHeader)
  //
  // Remove a memory block from block list
  inline void remove () ;
  //
  // Tree methods
  CABlockHeader* node_restore_left_balance (int _old_balance) ;
  CABlockHeader* node_restore_right_balance (int _old_balance) ;
  CABlockHeader* node_remove_leftmost (CABlockHeader** _leftmost) ;
  CABlockHeader* node_remove (CABlockHeader* _key) ;
  CABlockHeader* node_rotate_left () ;
  CABlockHeader* node_rotate_right () ;
  CABlockHeader* node_balance () ;
  CABlockHeader* node_insert (CABlockHeader* _key) ;

};

}

#endif // __pxx_chunk_allocator_block_header_hh__
