Eneboo - Documentación para desarrolladores
|
00001 /* -*- C++ -*- */ 00002 00003 #ifndef _ANSIWRAPPER_H_ 00004 #define _ANSIWRAPPER_H_ 00005 00006 #include <string.h> 00007 00008 /* 00009 * @class ANSIWrapper 00010 * @brief Provide ANSI C behavior for malloc & free. 00011 * 00012 * Implements all prescribed ANSI behavior, including zero-sized 00013 * requests & aligned request sizes to a double word (or long word). 00014 */ 00015 00016 00017 namespace HL { 00018 00019 template <class SuperHeap> 00020 class ANSIWrapper : public SuperHeap { 00021 public: 00022 00023 ANSIWrapper (void) 00024 {} 00025 00026 inline void * malloc (size_t sz) { 00027 if (sz < 2 * sizeof(size_t)) { 00028 // Make sure it's at least big enough to hold two pointers (and 00029 // conveniently enough, that's at least the size of a double, as 00030 // required by ANSI). 00031 sz = 2 * sizeof(size_t); 00032 } 00033 sz = align(sz); 00034 void * ptr = SuperHeap::malloc (sz); 00035 return ptr; 00036 } 00037 00038 inline void free (void * ptr) { 00039 if (ptr != 0) { 00040 SuperHeap::free (ptr); 00041 } 00042 } 00043 00044 inline void * calloc (const size_t s1, const size_t s2) { 00045 char * ptr = (char *) malloc (s1 * s2); 00046 if (ptr) { 00047 #if 1 00048 for (int i = 0; i < s1 * s2; i++) { 00049 ptr[i] = 0; 00050 } 00051 #else 00052 #error "Uncomment below." 00053 // memset (ptr, 0, s1 * s2); 00054 #endif 00055 } 00056 return (void *) ptr; 00057 } 00058 00059 inline void * realloc (void * ptr, const size_t sz) { 00060 if (ptr == 0) { 00061 return malloc (sz); 00062 } 00063 if (sz == 0) { 00064 free (ptr); 00065 return 0; 00066 } 00067 00068 size_t objSize = getSize (ptr); 00069 if (objSize == sz) { 00070 return ptr; 00071 } 00072 00073 // Allocate a new block of size sz. 00074 void * buf = malloc (sz); 00075 00076 // Copy the contents of the original object 00077 // up to the size of the new block. 00078 00079 size_t minSize = (objSize < sz) ? objSize : sz; 00080 if (buf) { 00081 memcpy (buf, ptr, minSize); 00082 } 00083 00084 // Free the old block. 00085 free (ptr); 00086 return buf; 00087 } 00088 00089 inline size_t getSize (void * ptr) { 00090 if (ptr) { 00091 return SuperHeap::getSize (ptr); 00092 } else { 00093 return 0; 00094 } 00095 } 00096 00097 private: 00098 inline static size_t align (size_t sz) { 00099 return (sz + (sizeof(double) - 1)) & ~(sizeof(double) - 1); 00100 } 00101 }; 00102 00103 } 00104 00105 #endif