about summary refs log tree commit diff
path: root/src/engine/shared/ringbuffer.h
blob: c47745285e80ea29d4ace6563237a113bbafda91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com.                */
#ifndef ENGINE_SHARED_RINGBUFFER_H
#define ENGINE_SHARED_RINGBUFFER_H

typedef struct RINGBUFFER RINGBUFFER;

class CRingBufferBase
{
	class CItem
	{
	public:
		CItem *m_pPrev;
		CItem *m_pNext;
		int m_Free;
		int m_Size;
	};

	CItem *m_pProduce;
	CItem *m_pConsume;

	CItem *m_pFirst;
	CItem *m_pLast;

	void *m_pMemory;
	int m_Size;
	int m_Flags;

	CItem *NextBlock(CItem *pItem);
	CItem *PrevBlock(CItem *pItem);
	CItem *MergeBack(CItem *pItem);
protected:
	void *Allocate(int Size);

	void *Prev(void *pCurrent);
	void *Next(void *pCurrent);
	void *First();
	void *Last();

	void Init(void *pMemory, int Size, int Flags);
	int PopFirst();
public:
	enum
	{
		// Will start to destroy items to try to fit the next one
		FLAG_RECYCLE=1
	};
};

template<typename T, int TSIZE, int TFLAGS=0>
class TStaticRingBuffer : public CRingBufferBase
{
	unsigned char m_aBuffer[TSIZE];
public:
	TStaticRingBuffer() { Init(); }

	void Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); }

	T *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); }
	int PopFirst() { return CRingBufferBase::PopFirst(); }

	T *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); }
	T *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); }
	T *First() { return (T*)CRingBufferBase::First(); }
	T *Last() { return (T*)CRingBufferBase::Last(); }
};

#endif