diff options
Diffstat (limited to 'src/mt/uniheap.h')
| -rw-r--r-- | src/mt/uniheap.h | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/src/mt/uniheap.h b/src/mt/uniheap.h new file mode 100644 index 0000000..39c3d34 --- /dev/null +++ b/src/mt/uniheap.h | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | /************************************************************************* | ||
| 2 | * | ||
| 3 | * HTCd - Copyright (C) 1998-2006 Henrik Rydberg | ||
| 4 | * | ||
| 5 | * This program is free software; you can redistribute it and/or modify | ||
| 6 | * it under the terms of the GNU General Public License as published by | ||
| 7 | * the Free Software Foundation; either version 2 of the License, or | ||
| 8 | * (at your option) any later version. | ||
| 9 | * | ||
| 10 | * This program is distributed in the hope that it will be useful, | ||
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| 13 | * GNU General Public License for more details. | ||
| 14 | * | ||
| 15 | * You should have received a copy of the GNU General Public License | ||
| 16 | * along with this program; if not, write to the Free Software | ||
| 17 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | ||
| 18 | */ | ||
| 19 | |||
| 20 | #ifndef UNIHEAPH | ||
| 21 | #define UNIHEAPH | ||
| 22 | |||
| 23 | #include <mt/mlock.h> | ||
| 24 | #include <malloc.h> | ||
| 25 | #include <string.h> | ||
| 26 | |||
| 27 | // NOTE - must be in extern/static scope, or zeroed before use | ||
| 28 | // by a call to init. constructors will fail badly. | ||
| 29 | // A minimum of sizeof(T)==4 is required. | ||
| 30 | // Furthermore, the upper limit of heap space is 1Gb. | ||
| 31 | |||
| 32 | template <int N> class uniheap { | ||
| 33 | public: | ||
| 34 | static const int maxchunks=24; | ||
| 35 | |||
| 36 | void init() { | ||
| 37 | head=0; | ||
| 38 | chunk=0; | ||
| 39 | nchunks=0; | ||
| 40 | memset(&mutex,0,sizeof(mutex_t)); | ||
| 41 | } | ||
| 42 | |||
| 43 | char* push() { MLOCK(mutex); char* p=news(); head=*(char**)p; return p; } | ||
| 44 | void pop(void* p) { MLOCK(mutex); *((char**)p)=head; head=(char*)p; } | ||
| 45 | int chunksize() const { return chunk; } | ||
| 46 | protected: | ||
| 47 | char* news() { | ||
| 48 | if(!head) { | ||
| 49 | if(!chunk) chunk=N<<4; | ||
| 50 | if(nchunks>=maxchunks) throw((int)0); | ||
| 51 | head=chunks[nchunks++]=(char*)malloc(chunk); | ||
| 52 | if(!head) throw((int)0); | ||
| 53 | for(int i=0;i<chunk-N;i+=N) *((char**)(head+i))=head+i+N; | ||
| 54 | *((char**)(head+chunk-N))=0; | ||
| 55 | chunk<<=1; | ||
| 56 | } | ||
| 57 | return head; | ||
| 58 | } | ||
| 59 | private: | ||
| 60 | char *head,*chunks[maxchunks]; | ||
| 61 | int chunk,nchunks; | ||
| 62 | mutex_t mutex; | ||
| 63 | }; | ||
| 64 | |||
| 65 | #endif | ||
