Ver código fonte

hashmap now has for each

master
FelixBrendel 5 anos atrás
pai
commit
58cb2a8ba2
3 arquivos alterados com 30 adições e 12 exclusões
  1. +19
    -0
      bucket_allocator.hpp
  2. +7
    -12
      hashmap.hpp
  3. +4
    -0
      test.cpp

+ 19
- 0
bucket_allocator.hpp Ver arquivo

@@ -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 <typename lambda>
void for_each(lambda p) {
free_list.sort();


+ 7
- 12
hashmap.hpp Ver arquivo

@@ -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 <typename key_type, typename value_type>
struct Hash_Map {
u32 current_capacity;
@@ -67,6 +55,13 @@ struct Hash_Map {
value_type object;
}* data;

template <typename lambda>
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;


+ 4
- 0
test.cpp Ver arquivo

@@ -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[]) {


Carregando…
Cancelar
Salvar