/*
 *  Copyright 2009 OpenSourceCodeStewardshipFoundation.org
 *  Licensed under GNU General Public License version 2
 *
 * Author: seanhalle@yahoo.com
 *
 * Created on November 14, 2009, 9:07 PM
 */

#ifndef _VMALLOC_H
#define	_VMALLOC_H

#include <malloc.h>
#include <inttypes.h>
#include "VMS_primitive_data_types.h"

#define SMALL_CHUNK_SIZE 32
#define SMALL_CHUNK_COUNT 4
#define LOWER_BOUND     128  //Biggest chunk size that is created for the small chunks
#define BIG_LOWER_BOUND 160  //Smallest chunk size that is created for the big chunks

#define LOG54 0.3219280948873623
#define LOG128 7

typedef struct _MallocProlog MallocProlog;

struct _MallocProlog
 {
   MallocProlog *nextChunkInFreeList;
   MallocProlog *prevChunkInFreeList;
   MallocProlog *nextHigherInMem;
   MallocProlog *nextLowerInMem;
 };
//MallocProlog
 
 typedef struct MallocArrays MallocArrays;

 struct MallocArrays
 {
     MallocProlog **smallChunks;
     MallocProlog **bigChunks;
     uint64       bigChunksSearchVector[2];
     void         *memSpace;
     uint32       containerCount;
 };
 //MallocArrays

typedef struct
 {
   MallocProlog *firstChunkInFreeList;
   int32         numInList; //TODO not used
 }
FreeListHead;

void *
VMS_int__malloc( size_t sizeRequested );
#define VMS_PI__malloc  VMS_int__malloc
#define VMS_WL__malloc  VMS_int__malloc /*TODO: Bug -- Not protected!! */
#define VMS_App__malloc VMS_int__malloc /*TODO: Bug -- Not protected!! */

void *
VMS_int__malloc_aligned( size_t sizeRequested );
#define VMS_PI__malloc_aligned VMS_int__malloc_aligned
#define VMS_WL__malloc_aligned VMS_int__malloc_aligned

void
VMS_int__free( void *ptrToFree );
#define VMS_PI__free  VMS_int__free
#define VMS_WL__free  VMS_int__free /*TODO: Bug -- Not protected!! */
#define VMS_App__free VMS_int__free /*TODO: Bug -- Not protected!! */



/*Allocates memory from the external system -- higher overhead
 */
void *
VMS_ext__malloc_in_ext( size_t sizeRequested );

/*Frees memory that was allocated in the external system -- higher overhead
 */
void
VMS_ext__free_in_ext( void *ptrToFree );


MallocArrays *
VMS_ext__create_free_list();

void
VMS_ext__free_free_list(MallocArrays *freeLists );

#endif