Eneboo - Documentación para desarrolladores
|
00001 /* -*- C++ -*- */ 00002 00003 #ifndef _FIRSTFITHEAP_H_ 00004 #define _FIRSTFITHEAP_H_ 00005 00006 template <class Super> 00007 class FirstFitHeap : public Super { 00008 public: 00009 00010 FirstFitHeap (void) 00011 : myFreeList (NULL) 00012 #ifndef NDEBUG 00013 ,nObjects (0) 00014 #endif 00015 { 00016 assert (classInvariant()); 00017 } 00018 00019 ~FirstFitHeap (void) 00020 { 00021 #if 1 00022 // Delete everything on the free list. 00023 void * ptr = myFreeList; 00024 while (ptr != NULL) { 00025 // assert (nObjects > 0); 00026 assert (ptr != NULL); 00027 void * oldptr = ptr; 00028 ptr = (void *) ((freeObject *) ptr)->next; 00029 Super::free (oldptr); 00030 #ifndef NDEBUG 00031 --nObjects; 00032 #endif 00033 } 00034 #endif 00035 } 00036 00037 inline void * malloc (size_t sz) { 00038 // Check the free list first. 00039 assert (classInvariant()); 00040 void * ptr = myFreeList; 00041 if (ptr == NULL) { 00042 assert (nObjects == 0); 00043 ptr = Super::malloc (sz); 00044 } else { 00045 assert (nObjects > 0); 00046 freeObject * p = myFreeList; 00047 freeObject * prev = NULL; 00048 while ((p != NULL) && (getSize((void *) p) < sz)) { 00049 prev = p; 00050 p = p->next; 00051 } 00052 if (p == NULL) { 00053 ptr = Super::malloc (sz); 00054 } else { 00055 assert (getSize((void *) p) >= sz); 00056 if (prev == NULL) { 00057 myFreeList = p->next; 00058 } else { 00059 assert (prev->next == p); 00060 prev->next = p->next; 00061 } 00062 #ifndef NDEBUG 00063 nObjects--; 00064 #endif 00065 ptr = p; 00066 } 00067 } 00068 assert (classInvariant()); 00069 return ptr; 00070 } 00071 00072 inline void free (void * ptr) { 00073 // Add this object to the free list. 00074 assert (ptr != NULL); 00075 assert (classInvariant()); 00076 #ifndef NDEBUG 00077 nObjects++; 00078 #endif 00079 freeObject * p = myFreeList; 00080 freeObject * prev = NULL; 00081 // Insert the object "in order". 00082 #if 1 00083 while ((p != NULL) & (p <= ptr)) { 00084 prev = p; 00085 p = p->next; 00086 } 00087 #endif 00088 if (prev == NULL) { 00089 ((freeObject *) ptr)->next = myFreeList; 00090 myFreeList = (freeObject *) ptr; 00091 } else { 00092 ((freeObject *) ptr)->next = prev->next; 00093 prev->next = (freeObject *) ptr; 00094 } 00095 assert (classInvariant()); 00096 } 00097 00098 private: 00099 00100 int classInvariant (void) { 00101 return (((myFreeList == NULL) && (nObjects == 0)) 00102 || ((myFreeList != NULL) && (nObjects > 0))); 00103 } 00104 00105 class freeObject { 00106 public: 00107 freeObject * next; 00108 }; 00109 00110 freeObject * myFreeList; 00111 #ifndef NDEBUG 00112 int nObjects; 00113 #endif 00114 00115 }; 00116 00117 #endif