code reorg
[csql.git] / src / storage / FixedHeapAllocator.cxx
blobaaa8cf97f29608fcae4131d90dd4e85a04771efb
1 #include <HeapAllocator.h>
2 #include <ErrorType.h>
3 #include <Debug.h>
5 void FixedHeapAllocator::initializeInfo(void *ptr)
7 *(void **)ptr = top;
8 top = ptr;
9 usedBytes = 0;
10 offset = (char*)top+PAGEINFOSIZE;
11 *(short*)((char*)offset+1) = pageSize- PAGEINFOSIZE-BLOCKINFOSIZE;
14 void FixedHeapAllocator::init(int pSize,int allocSize)
16 void *ptr;
17 ptr = ::calloc(pSize,1);
18 if(ptr == NULL)
20 printError(ErrOS, "Unable to allocate %d bytes", pSize);
21 return;
23 allocateSize = allocSize;
24 pageSize = pSize;
25 initializeInfo(ptr);
26 isInitialized = 1;
27 pageCounter++;
31 void* FixedHeapAllocator::allocate()
33 void *allocateptr, *ptr, *freeSpaceDetector, *pageDetector;
34 short int pageSizeCounter = 0, add;
35 short int isFound = 0;
37 if(isInitialized != 1)
39 printError(ErrBadCall, "Allocator is not initialized");
40 return NULL;
42 if(allocateSize > ( pageSize - PAGEINFOSIZE-(2*BLOCKINFOSIZE) ))
44 printf("The requested size is greater than the page Size");
45 return NULL;
47 //TODO::we will implement mode later for this fixed size allocator
48 //printf("\ninside allocate offset = %u\tpagesize= %d\tusedmemory=%d\tmemoryrequested = %d",offset,pageSize,usedBytes, allocateSize );
49 if( ( usedBytes + allocateSize ) > ( pageSize - PAGEINFOSIZE ) )
51 printDebug(DM_Alloc, "Current page exhausted. allocating new page");
52 ptr = calloc(pageSize,1);
53 if(ptr == NULL)
55 printError(ErrOS, "Unable to allocate %d bytes", pageSize);
56 return NULL;
58 pageCounter++;
59 initializeInfo(ptr);
61 allocateptr = offset;
62 offset = (char *)offset+allocateSize ;
63 usedBytes += allocateSize ;
64 //printf("\nafter allocate offset = %u\tusedmemory=%d\tmemoryrequested = %d\treturn ptr = %u",offset,usedBytes, allocateSize,allocateptr);
65 return (allocateptr);
68 void FixedHeapAllocator::deAllocate(void *ptr)
72 void FixedHeapAllocator::destroy()
74 void *ptr, *temp;
75 ptr = top;
76 unsigned int add;
77 while(ptr)
79 temp = ptr;
80 ptr = *(void **)ptr;
81 //printf("deallocating %u",temp);
82 free(temp);
86 /*int main()
88 cout << "This is the main program";
89 int bsize;
90 FixedHeapAllocator mAllocator;
91 mAllocator.init(50,10);
92 int i = 0, choice;
93 unsigned int ptr;
94 while(true)
96 cout << "enter the choice that u want";
97 cin>> choice;
98 if(choice == 1)
100 // cout << "please enter the memory in bytes that u want to allocate";
101 // cin >> bsize;
102 mAllocator.allocate();
104 else if(choice == 2)
106 cout << "please enter the memory address to deallocate";
107 cin >> ptr;
109 else
111 // exit(1);
112 break;
116 mAllocator.destroy();
117 exit(1);