File indexing completed on 2024-03-24 16:06:01
0001 /* 0002 This file is part of kdev-pg 0003 Copyright 2005, 2006 Roberto Raggi <roberto@kdevelop.org> 0004 0005 Permission to use, copy, modify, distribute, and sell this software and its 0006 documentation for any purpose is hereby granted without fee, provided that 0007 the above copyright notice appear in all copies and that both that 0008 copyright notice and this permission notice appear in supporting 0009 documentation. 0010 0011 The above copyright notice and this permission notice shall be included in 0012 all copies or substantial portions of the Software. 0013 0014 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 0015 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 0016 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 0017 KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 0018 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 0019 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 0020 */ 0021 //krazy:excludeall=inline 0022 #ifndef KDEV_PG_MEMORY_POOL 0023 #define KDEV_PG_MEMORY_POOL 0024 0025 #include <QtGlobal> 0026 0027 #include <string.h> 0028 #include <stdlib.h> 0029 0030 namespace KDevPG 0031 { 0032 0033 class BlockType 0034 { 0035 public: 0036 qint64 blockSize; 0037 BlockType *chain; 0038 char *data; 0039 char *ptr; 0040 char *end; 0041 0042 inline void init(int block_size = 256) 0043 { 0044 blockSize = block_size; 0045 chain = nullptr; 0046 data = (char*) malloc(blockSize); 0047 ptr = data; 0048 end = data + block_size; 0049 } 0050 0051 inline void init0(int block_size = 256) 0052 { 0053 init(block_size); 0054 memset(data, '\0', block_size); 0055 } 0056 0057 inline void destroy() 0058 { 0059 if (chain) { 0060 chain->destroy(); 0061 free(chain); 0062 } 0063 0064 free(data); 0065 } 0066 0067 inline void *allocate(size_t size, BlockType **right_most) 0068 { 0069 if (end < ptr + size) { 0070 // assert( size < block_size ); 0071 0072 if (!chain) { 0073 chain = (BlockType*) malloc(sizeof(BlockType)); 0074 chain->init0(blockSize << 2); 0075 } 0076 0077 return chain->allocate(size, right_most); 0078 } 0079 0080 char *r = ptr; 0081 ptr += size; 0082 0083 if (right_most) 0084 *right_most = this; 0085 0086 return r; 0087 } 0088 0089 }; 0090 0091 class MemoryPool 0092 { 0093 public: 0094 BlockType blk; 0095 BlockType *rightMost; 0096 0097 inline MemoryPool() { blk.init0(); rightMost = &blk; } 0098 inline ~MemoryPool() { blk.destroy(); } 0099 0100 inline void *allocate(size_t size) 0101 { return rightMost->allocate(size, &rightMost); } 0102 }; 0103 0104 } 0105 0106 #endif