/*************************************************
* Managed Allocator Header File                  *
* (C) 1999-2002 The Botan Project                *
*************************************************/

#ifndef BOTAN_MANAGED_ALLOCATOR_H__
#define BOTAN_MANAGED_ALLOCATOR_H__

#include <botan/secalloc.h>
#include <botan/exceptn.h>
#include <botan/mutex.h>
#include <vector>
#include <map>

namespace Botan {

/*************************************************
* Managed Allocator                              *
*************************************************/
class ManagedAllocator : public SecureAllocator
   {
   public:
      struct Buffer { u32bit length; void* data; };

      void* allocate(u32bit) const;
      void deallocate(void*, u32bit) const;

      ManagedAllocator(bool, u32bit = 1024);
      ~ManagedAllocator();
   private:

      static const u32bit ALIGN_TO = 8;
      virtual void* alloc_block(u32bit) const = 0;
      virtual void dealloc_block(void*, u32bit) const = 0;

      void* find_free_block(u32bit) const;
      void defrag_free_list() const;
      u32bit find_buffer(void*) const;

      u32bit round_up(u32bit) const;
      bool same_buffer(Buffer&, Buffer&) const;
      bool overlap(Buffer, Buffer) const;
      void remove_empty_buffers(std::vector<Buffer>&) const;

      const u32bit pref_size;
      mutable std::map<void*, Buffer*> allocated;
      mutable std::vector<Buffer> free_list;
      mutable std::vector<Buffer> buffer_list;
      mutable Mutex* lock;
   };

}

#endif
