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