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