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