44
55#include " std/allocator.hpp"
66#include " syscalls/syscalls.h"
7+ #include " std/memory.h"
78
89template <typename T>
910class IndexMap {
@@ -12,21 +13,30 @@ class IndexMap {
1213 IndexMap () : items(0 ), count(0 ), capacity(0 ) {
1314 }
1415
16+ IndexMap<T>* operator =(const IndexMap<T>& orig){
17+ this ->count = orig.count ;
18+ this ->capacity = orig.capacity ;
19+ void *mem = (void *)malloc (sizeof (T) * (capacity + 1 ));
20+ items = reinterpret_cast <T*>(mem);
21+ memcpy (this ->items , orig.items , sizeof (T) * (capacity + 1 ));
22+ return this ;
23+ }
24+
1525 IndexMap (uint32_t capacity) : count(0 ), capacity(capacity) {
1626 if (capacity == 0 ) {
1727 items = 0 ;
1828 return ;
1929 }
20- void *mem = (void *)malloc (sizeof (T) * capacity);
30+ void *mem = (void *)malloc (sizeof (T) * ( capacity + 1 ) );
2131 items = reinterpret_cast <T*>(mem);
32+ default_val = &items[capacity];
2233 }
2334
2435 ~IndexMap () {
25- // TODO: Deallocation has not been changed since this code was copied off Array
26- if (count == 0 ) return ;
27- for (uint32_t i = 0 ; i < count; i++)
36+ if (capacity == 0 ) return ;
37+ for (uint32_t i = 0 ; i < capacity; i++)
2838 items[i].~T ();
29- free (items, sizeof (T) * count );
39+ if (items) free (items, sizeof (T) * (capacity + 1 ) );
3040 }
3141
3242 bool add (const uint32_t index, const T& value) {
@@ -36,15 +46,22 @@ class IndexMap {
3646 return true ;
3747 }
3848
39- // TODO: we need a function for checking if a value exists
40- T& operator [](uint32_t i) { return items[i]; }
41- const T& operator [](uint32_t i) const { return items[i]; }
49+ T& operator [](uint32_t i) {
50+ if (i >= capacity) return *default_val;
51+ return items[i];
52+ }
53+ const T& operator [](uint32_t i) const {
54+ if (i >= capacity) return *default_val;
55+ return items[i];
56+ }
4257 uint32_t size () const { return count; }
4358 uint32_t max_size () const { return capacity; }
4459
4560 T* items;
61+ T* default_val;
4662
4763private:
4864 uint32_t count;
4965 uint32_t capacity;
50- };
66+ };
67+ // TEST: when assigning an indexmap (like in xhci's endpoint_map), it gets copied. Make sure the old one gets freed
0 commit comments