diff --git a/bucket_allocator.hpp b/bucket_allocator.hpp index 499250c..9137408 100644 --- a/bucket_allocator.hpp +++ b/bucket_allocator.hpp @@ -54,6 +54,25 @@ public: free(buckets); } + u32 count_elements() { + free_list.sort(); + type* val; + u32 count = 0; + for (u32 i = 0; i < next_bucket_index; ++i) { + for (u32 j = 0; j < bucket_size; ++j) { + val = buckets[i]+j; + if (free_list.sorted_find(val) == -1) + count++; + } + } + for (u32 j = 0; j < next_index_in_latest_bucket; ++j) { + val = buckets[next_bucket_index]+j; + if (free_list.sorted_find(val) == -1) + count++; + } + return count; + } + template void for_each(lambda p) { free_list.sort(); diff --git a/hashmap.hpp b/hashmap.hpp index 39c04b2..2a016a9 100644 --- a/hashmap.hpp +++ b/hashmap.hpp @@ -6,7 +6,6 @@ #include "types.hpp" #include "arraylist.hpp" - u32 hm_hash(const char* str) { u32 value = str[0] << 7; s32 i = 0; @@ -29,12 +28,10 @@ u32 hm_hash(void* ptr) { return ((u64)ptr * 2654435761) % 4294967296; } - inline bool hm_objects_match(const char* a, const char* b) { return strcmp(a, b) == 0; } - inline bool hm_objects_match(char* a, char* b) { return strcmp(a, b) == 0; } @@ -43,15 +40,6 @@ inline bool hm_objects_match(void* a, void* b) { return a == b; } - -#define for_hash_map(hm) \ - if (decltype((hm).data[0].original) key = 0); else \ - if (decltype((hm).data[0].object) value = 0); else \ - for(u32 index = 0; index < (hm).current_capacity; ++index) \ - if (!((!(hm).data[index].deleted) && \ - (key = (hm).data[index].original) && \ - (value = (hm).data[index].object))); else - template struct Hash_Map { u32 current_capacity; @@ -67,6 +55,13 @@ struct Hash_Map { value_type object; }* data; + template + void for_each(lambda p) { + for(u32 index = 0; index < current_capacity; ++index) + if (data[index].occupancy == HM_Cell::Occupancy::Occupied) + p(data[index].original, data[index].object, index); + } + void alloc(u32 initial_capacity = 8) { current_capacity = initial_capacity; cell_count = 0; diff --git a/test.cpp b/test.cpp index 7efae1c..a887c98 100644 --- a/test.cpp +++ b/test.cpp @@ -111,6 +111,10 @@ auto test_hm() -> void { assert(h2.get_object({.x = 1, .y = 2, .z = 3}) == 1, "value should be correct"); assert(h2.get_object({.x = 3, .y = 3, .z = 3}) == 3, "value should be correct"); + + h2.for_each([] (Key k, u32 v, u32 i) { + print("%{s32} %{u32} %{u32}\n", k.x, v, i); + }); } s32 main(s32 argc, char* argv[]) {