Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1805 yogev_ezra 1
#ifndef __MENUET_HEAP_H_INCLUDED_
2
#define __MENUET_HEAP_H_INCLUDED_
3
 
4
#include 
5
#include 
6
 
7
// Menuet memory heap interface.
8
 
9
namespace Menuet   // All menuet functions, types and data are nested in the (Menuet) namespace.
10
{
11
	void *Alloc(unsigned int size);
12
	void *ReAlloc(void *mem, unsigned int size);
13
	void Free(void *mem);
14
}
15
 
16
#ifdef __MENUET__
17
 
18
namespace Menuet
19
{
20
 
21
// Global variables
22
 
23
	MemoryHeap::TFreeSpace _MenuetFreeSpace;
24
	MemoryHeap::TMemBlock  _MenuetMemBlock;
25
	TMutex _MemHeapMutex = MENUET_MUTEX_INIT;
26
 
27
// Functions
28
 
29
	void *_HeapInit(void *begin, void *use_end, void *end)
30
	{
31
		MemoryHeap::InitFreeSpace(_MenuetFreeSpace);
32
		_MenuetMemBlock = MemoryHeap::CreateBlock(begin, end, _MenuetFreeSpace);
33
		unsigned int use_beg = (unsigned int)MemoryHeap::BlockBegin(_MenuetMemBlock) +
34
					MemoryHeap::BlockAddSize - MemoryHeap::BlockEndSize;
35
		unsigned int use_size = (unsigned int)use_end;
36
		if (use_size <= use_beg) return 0;
37
		else use_size -= use_beg;
38
		return MemoryHeap::Alloc(_MenuetFreeSpace, use_size);
39
	}
40
 
41
	bool _SetUseMemory(unsigned int use_mem);
42
 
43
	int _RecalculateUseMemory(unsigned int use_mem);
44
 
45
	void *Alloc(unsigned int size)
46
	{
47
		if (!size) return 0;
48
		Lock(&_MemHeapMutex);
49
		void *res = MemoryHeap::Alloc(_MenuetFreeSpace, size);
50
		if (!res)
51
		{
52
			unsigned use_mem = (unsigned int)MemoryHeap::BlockEndFor(_MenuetMemBlock, size);
53
			if (_SetUseMemory(_RecalculateUseMemory(use_mem)))
54
			{
55
				res = MemoryHeap::Alloc(_MenuetFreeSpace, size);
56
			}
57
		}
58
		UnLock(&_MemHeapMutex);
59
		return res;
60
	}
61
 
62
	void *ReAlloc(void *mem, unsigned int size)
63
	{
64
		Lock(&_MemHeapMutex);
65
		void *res = MemoryHeap::ReAlloc(_MenuetFreeSpace, mem, size);
66
		if (!res && size)
67
		{
68
			unsigned use_mem = (unsigned int)MemoryHeap::BlockEndFor(_MenuetMemBlock, size);
69
			if (_SetUseMemory(_RecalculateUseMemory(use_mem)))
70
			{
71
				res = MemoryHeap::ReAlloc(_MenuetFreeSpace, mem, size);
72
			}
73
		}
74
		UnLock(&_MemHeapMutex);
75
		return res;
76
	}
77
 
78
	void Free(void *mem)
79
	{
80
		Lock(&_MemHeapMutex);
81
		MemoryHeap::Free(_MenuetFreeSpace, mem);
82
		UnLock(&_MemHeapMutex);
83
	}
84
 
85
	void _FreeAndThreadFinish(void *mem, int *exit_proc_now);
86
}
87
 
88
#endif  // def  __MENUET__
89
 
90
#endif  // ndef __MENUET_HEAP_H_INCLUDED_