about summary refs log tree commit diff
path: root/src/engine/ringbuffer.h
blob: 3208efbf2274285ad19a23b2a091984d956832c3 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

// TODO: remove all the allocations from this class
class ring_buffer
{
public:
	struct item
	{
		item *next;
		item *prev;
		int size;
		unsigned char *data() { return (unsigned char *)(this+1); }
	};
	
	item *first_item;
	item *last_item;
	
	unsigned buffer_size;
	
	ring_buffer()
	{
		first_item = 0;
		last_item = 0;
		buffer_size = 0;
	}
	
	~ring_buffer()
	{
		reset();
	}
	
	void reset()
	{
		// clear all
		while(first())
			pop_first();
	}
	
	void *alloc(int size)
	{
		item *i = (item*)mem_alloc(sizeof(item)+size, 1);
		i->size = size;
		
		i->prev = last_item;
		i->next = 0;
		if(last_item)
			last_item->next = i;
		else
			first_item = i;
		last_item = i;
		
		buffer_size += size;
		return i->data();
	}
	
	item *first()
	{
		return first_item;
	}

	/*
	void *peek_data()
	{
		if(!first)
			return 0;
		return (void*)(first+1);
	}*/
	
	void pop_first()
	{
		if(first_item)
		{
			item *next = first_item->next;
			buffer_size -= first_item->size;
			mem_free(first_item);
			first_item = next;
			if(first_item)
				first_item->prev = 0;
			else
				last_item = 0;
		}
	}
	
	unsigned size() { return buffer_size; }
};