xref: /haiku/headers/private/media/TList.h (revision 7120e97489acbf17d86d3f33e3b2e68974fd4b23)
1 #ifndef _MEDIA_T_LIST_H
2 #define _MEDIA_T_LIST_H
3 
4 #include "debug.h"
5 
6 template<class value> class List
7 {
8 public:
9 	List()
10 	 :	item_max(INIT_COUNT),
11 	 	item_count(0),
12 	 	item_iter(-1),
13 	 	items((value **)malloc(sizeof(value *) * INIT_COUNT))
14 	{
15 		ASSERT(items);
16 	}
17 
18 	~List()
19 	{
20 	}
21 
22 	List(const List<value> &other)
23 	{
24 		*this = other;
25 	}
26 
27 	List<value> &operator=(const List<value> &other)
28 	{
29 		MakeEmpty();
30 		free(items);
31 		item_max = other.item_max;
32 	 	item_count = other.item_count;
33 		items = (value **)malloc(sizeof(value *) * item_max);
34 		ASSERT(items);
35 	 	for (int i = 0; i < item_count; i++) {
36 	 		items[i] = new value;
37 	 		*items[i] = *other.items[i];
38 	 	}
39 	 	return *this;
40 	}
41 
42 	bool Insert(const value &v)
43 	{
44 		if (item_count == item_max) {
45 			item_max *= 2;
46 			items = (value **)realloc(items, sizeof(value *) * item_max);
47 			ASSERT(items);
48 		}
49 		items[item_count] = new value;
50 		*items[item_count] = v;
51 		item_count++;
52 		return true;
53 	}
54 
55 	bool Get(int32 index, value **v)
56 	{
57 		if (index < 0 || index >= item_count)
58 			return false;
59 		*v = items[index];
60 		return true;
61 	}
62 
63 	bool Remove(int32 index)
64 	{
65 		if (index < 0 || index >= item_count)
66 			return false;
67 		delete items[index];
68 		item_count--;
69 		items[index] = items[item_count];
70 		if (index == item_iter)
71 			item_iter--;
72 		return true;
73 	}
74 
75 	int Find(const value &v)
76 	{
77 		for (int i = 0; i < item_count; i++)
78 			if (*items[i] == v)
79 				return i;
80 		return -1;
81 	}
82 
83 	int CountItems()
84 	{
85 		return item_count;
86 	}
87 
88 	bool IsEmpty()
89 	{
90 		return item_count == 0;
91 	}
92 
93 	void MakeEmpty()
94 	{
95 		if (items != 0) {
96 			for (int i = 0; i < item_count; i++) {
97 				delete items[i];
98 			}
99 			item_count = 0;
100 		}
101 	}
102 
103 	void Rewind()
104 	{
105 		item_iter = -1;
106 	}
107 
108 	bool GetNext(value **v)
109 	{
110 		item_iter++;
111 		return Get(item_iter, v);
112 	}
113 
114 	bool RemoveCurrent()
115 	{
116 		return Remove(item_iter);
117 	}
118 
119 private:
120 	enum { INIT_COUNT=32 };
121 	int item_max;
122 	int item_count;
123 	int item_iter;
124 	value **items;
125 };
126 
127 #endif // _MEDIA_T_LIST_H
128