#include        "defs.h"


void    bitmap_init(__in pbitmap_struct pbitmap){
        pbitmap->buffer = dlmalloc(0);
        pbitmap->length = 0;       
}
void    bitmap_set_bit(__in pbitmap_struct pbitmap, __in unsigned long bit){
        unsigned int index;
        unsigned int offset;
        unsigned long new_size;
        unsigned int *ptr;
        void         *new_buffer;
        
        offset = bit / (sizeof(unsigned int) * 8);
        index  = bit % (sizeof(unsigned int) * 8);
        
        new_size = (offset+1) * sizeof(unsigned int);
        
        if (pbitmap->length < new_size){
                new_buffer = dlmalloc(new_size);
                memset(new_buffer, 0, new_size);
                memcpy(new_buffer, pbitmap->buffer, pbitmap->length);
                dlfree(pbitmap->buffer);
                pbitmap->buffer = new_buffer;
                pbitmap->length = new_size;
        }
                
        ptr = pbitmap->buffer;
        ptr[offset] |= (1 << index);
                
}
void    bitmap_clear_bit(__in pbitmap_struct pbitmap, __in unsigned long bit){
        unsigned int index;
        unsigned int offset;
        unsigned long new_size;
        unsigned int *ptr;
        
        offset = bit / (sizeof(unsigned int) * 8);
        index  = bit % (sizeof(unsigned int) * 8);        
        
        new_size = (offset+1) * sizeof(unsigned int);
        if (pbitmap->length < new_size) return;
        
        ptr = pbitmap->buffer;
        ptr[offset] &= ~(1 << index);        
}

unsigned long bitmap_check_bit(__in pbitmap_struct pbitmap, __in unsigned long bit){
        unsigned int index;
        unsigned int offset;
        unsigned long new_size;
        unsigned int *ptr;
        
        offset = bit / (sizeof(unsigned int) * 8);
        index  = bit % (sizeof(unsigned int) * 8);        
        
        new_size = (offset+1) * sizeof(unsigned int);
        if (pbitmap->length < new_size) return 0;
        
        ptr = pbitmap->buffer;
        if (ptr[offset] & (1 << bit)) return 1;
        return 0;
}        
void    bitmap_destroy(__in pbitmap_struct pbitmap){
        if (pbitmap){
                if (pbitmap->buffer){
                        memset(pbitmap->buffer, 0, pbitmap->length);
                        dlfree(pbitmap->buffer);
                }
                pbitmap->buffer = 0;
                pbitmap->length = 0;
        }
}