1 #ifndef _MEDIA_T_MAP_H 2 #define _MEDIA_T_MAP_H 3 4 5 #include "debug.h" 6 7 template<class key, class value> class Map 8 { 9 public: 10 Map() 11 : item_max(INIT_COUNT), 12 item_count(0), 13 item_iter(-1), 14 items((ent **)malloc(sizeof(ent *) * INIT_COUNT)) 15 { 16 ASSERT(items); 17 } 18 19 ~Map() 20 { 21 MakeEmpty(); 22 free(items); 23 } 24 25 Map(const Map<key, value> &other) 26 { 27 *this = other; 28 } 29 30 Map<key, value> &operator=(const Map<key, value> &other) 31 { 32 MakeEmpty(); 33 free(items); 34 item_max = other.item_max; 35 item_count = other.item_count; 36 items = (ent **)malloc(sizeof(ent *) * item_max); 37 ASSERT(items); 38 for (int i = 0; i < item_count; i++) { 39 items[i] = new ent; 40 items[i]->k = other.items[i]->k; 41 items[i]->v = other.items[i]->v; 42 } 43 return *this; 44 } 45 46 bool Insert(const key &k, const value &v) 47 { 48 if (item_count == item_max) { 49 item_max *= 2; 50 items = (ent **)realloc(items, sizeof(ent *) * item_max); 51 ASSERT(items); 52 } 53 items[item_count] = new ent; 54 items[item_count]->k = k; 55 items[item_count]->v = v; 56 item_count++; 57 return true; 58 } 59 60 bool Get(const key &k, value **v) 61 { 62 for (int i = 0; i < item_count; i++) { 63 if (items[i]->k == k) { 64 *v = &items[i]->v; 65 return true; 66 } 67 } 68 return false; 69 } 70 71 bool Remove(const key &k) { 72 for (int i = 0; i < item_count; i++) 73 if (items[i]->k == k) 74 return _Remove(i); 75 return false; 76 } 77 78 int Find(const value &v) 79 { 80 for (int i = 0; i < item_count; i++) 81 if (items[i]->v == v) 82 return i; 83 return -1; 84 } 85 86 bool Has(const key &k) 87 { 88 for (int i = 0; i < item_count; i++) 89 if (items[i]->k == k) 90 return true; 91 return false; 92 } 93 94 bool IsEmpty() 95 { 96 return item_count == 0; 97 } 98 99 void MakeEmpty() 100 { 101 if (items != 0) { 102 for (int i = 0; i < item_count; i++) { 103 delete items[i]; 104 } 105 item_count = 0; 106 } 107 } 108 109 void Rewind() 110 { 111 item_iter = -1; 112 } 113 114 bool GetNext(value **v) 115 { 116 item_iter++; 117 return _Get(item_iter, v); 118 } 119 120 bool GetCurrentKey(key **k) 121 { 122 if (item_iter < 0 || item_iter >= item_count) 123 return false; 124 *k = &items[item_iter]->k; 125 return true; 126 } 127 128 bool RemoveCurrent() 129 { 130 return _Remove(item_iter); 131 } 132 133 private: 134 bool _Get(int32 index, value **v) 135 { 136 if (index < 0 || index >= item_count) 137 return false; 138 *v = &items[index]->v; 139 return true; 140 } 141 142 bool _Remove(int32 index) 143 { 144 if (index < 0 || index >= item_count) 145 return false; 146 delete items[index]; 147 item_count--; 148 items[index] = items[item_count]; 149 if (index == item_iter) 150 item_iter--; 151 return true; 152 } 153 154 private: 155 enum { INIT_COUNT=32 }; 156 int item_max; 157 int item_count; 158 int item_iter; 159 struct ent { 160 key k; 161 value v; 162 }; 163 ent **items; 164 }; 165 166 #endif // _MEDIA_T_MAP_H 167