#include <lib/Alloc.h>

Alloc::Alloc() {
    alloc_size = 0;
    flags = 0x0;
    for (int i = 0; i < 8; i++)
      chunks[i] = (void *) 0x0;
    };

Alloc::Alloc(int size) {
    Alloc();
    alloc_size = size;
    };

Alloc::~Alloc() { clear(); }
void Alloc::setSize(int size) { clear(); alloc_size = size; }

void * Alloc::allocate() {
    void * ptr;
    
    if (0 == alloc_size)
      return NULL;

    int i = 0;
    uint8_t flag_lookup = 0x1;
    
    while((i < 8) && ((flags & flag_lookup) == 0))
    {
      flag_lookup <<= 1;
      i++;
    }

    if (i == 8) 
      ptr = kmalloc(alloc_size,-2);
    else
    {
      flags ^= flag_lookup;
      ptr = chunks[i];
    }

    return ptr;
};

void Alloc::deallocate(void * ptr) {
    
    int i = 0;
    uint8_t flag_lookup = 0x1;

    while((i < 8) && ((flags & flag_lookup) != 0))
    {
      flag_lookup <<= 1;
      i++;
    }

    if (i == 8)
       kfree(ptr);
    else
    {
      flags ^= flag_lookup;
      chunks[i] = ptr;
    }
};

void Alloc::clear() {
    
    uint8_t flag_lookup = 0x1;
    
    for (int i = 0; i < 8; i++)
    {
      if (flags & flag_lookup != 0)
      {
	flags ^= flag_lookup;
	chunks[i] = NULL;
      }
      flag_lookup <<= 1;
    }
};

