1 //---------------------------------------------------------------------- 2 // This software is part of the OpenBeOS distribution and is covered 3 // by the MIT License. 4 // 5 // Copyright (c) 2003 Tyler Dauwalder, tyler@dauwalder.net 6 //--------------------------------------------------------------------- 7 8 #ifndef _UDF_MEMORY_CHUNK_H 9 #define _UDF_MEMORY_CHUNK_H 10 11 #include <malloc.h> 12 13 #include <util/kernel_cpp.h> 14 15 /*! Simple class to encapsulate the boring details of allocating 16 and deallocating a chunk of memory. 17 18 The main use for this class is cleanly and simply allocating 19 arbitrary chunks of data on the stack. 20 */ 21 class MemoryChunk { 22 public: 23 MemoryChunk(uint32 blockSize) 24 : fSize(blockSize) 25 , fData(malloc(blockSize)) 26 , fOwnsData(true) 27 { 28 } 29 30 MemoryChunk(uint32 blockSize, void *blockData) 31 : fSize(blockSize) 32 , fData(blockData) 33 , fOwnsData(false) 34 { 35 } 36 37 ~MemoryChunk() 38 { 39 if (fOwnsData) 40 free(Data()); 41 } 42 43 uint32 Size() { return fSize; } 44 void* Data() { return fData; } 45 status_t InitCheck() { return Data() ? B_OK : B_NO_MEMORY; } 46 47 private: 48 MemoryChunk(); 49 MemoryChunk(const MemoryChunk&); 50 MemoryChunk& operator=(const MemoryChunk&); 51 52 uint32 fSize; 53 void *fData; 54 bool fOwnsData; 55 }; 56 57 template <uint32 size> 58 class StaticMemoryChunk { 59 public: 60 uint32 Size() { return size; } 61 void* Data() { return reinterpret_cast<void*>(fData); } 62 status_t InitCheck() { return B_OK; } 63 64 private: 65 uint8 fData[size]; 66 }; 67 68 #endif // _UDF_MEMORY_CHUNK_H 69