view dowa/d_memory.c @ 2:8a43dedbe530

[Dowa] Added HashMap and Updated Arena naming.
author June Park <parkjune1995@gmail.com>
date Wed, 24 Sep 2025 13:15:32 -0700
parents adcfad6e86fb
children 2758f5527d2b
line wrap: on
line source

#include "dowa.h"

// --- Arena --- //
Dowa_PArena Dowa_Arena_Initialize(size_t capacity)
{
  Dowa_PArena p_arena;
  p_arena = malloc(capacity);
  if (p_arena == NULL)
  {
    perror("malloc");
    return NULL;
  }
  p_arena->offset = 0;
  p_arena->capacity = capacity;
  return p_arena;
}

void *Dowa_Arena_Allocate(Dowa_PArena p_arena, size_t size)
{
  if (p_arena->offset + size > p_arena->capacity)
  {
    return NULL;
  }
  void *currnet_ptr = p_arena->buffer + p_arena->offset;
  p_arena->offset += size;
  return currnet_ptr;
}

void Dowa_Arena_Free(Dowa_PArena p_arena)
{
  if (p_arena) {
    free(p_arena->buffer);
    free(p_arena);
  }
}

// --- HashMap --- //
Dowa_PHashMap Dowa_HashMap_Create(size_t capacity)
{
  Dowa_PHashMap p_hash_map;
  p_hash_map = malloc(sizeof(Dowa_HashMap));
  if (p_hash_map == NULL)
  {
    return NULL;
  }
  p_hash_map->entries = calloc(capacity, sizeof *p_hash_map->entries);
  if (p_hash_map->entries == NULL)
  {
    free(p_hash_map);
    return NULL;
  }
  p_hash_map->capacity = capacity;
  p_hash_map->current_capacity = 0;
  return p_hash_map;
}

int32 Dowa_HashMap_GetPosition(Dowa_PHashMap p_hash_map, char *key)
{
  int32 hash_val = HASH_KEY_NUMBER;
  int32 c;
  while ((c = *key++))
  {
    hash_val = (hash_val << 5) + hash_val + c;
  }
  return hash_val % p_hash_map->capacity;
}

void Dowa_HashMap_PushValue(Dowa_PHashMap p_hash_map, char *key, void *value, size_t value_size)
{
  int idx = Dowa_HashMap_GetPosition(p_hash_map, key);
  Dowa_PHashEntry entry = p_hash_map->entries[idx];
  if (entry)
  {
    free(entry->key);
    free(entry->buffer);
  }
  else 
  {
    entry = malloc(sizeof(Dowa_HashEntry));
    if (entry == NULL)
    {
      perror("malloc");
      return;
    }
    p_hash_map->entries[idx] = entry;
  }
  entry->key = strdup(key);
  entry->buffer = malloc(value_size);
  if (entry->buffer == NULL)
  {
    perror("malloc");
    return;
  }
  entry->capacity = value_size;
  memcpy(entry->buffer, value, value_size);
  p_hash_map->current_capacity++;
}

void Dowa_HashMap_PopKey(Dowa_PHashMap p_hash_map, char *key)
{
  int idx = Dowa_HashMap_GetPosition(p_hash_map, key);
  Dowa_PHashEntry entry = p_hash_map->entries[idx];
  if (entry)
  {
    free(entry->key);
    free(entry->buffer);
    free(entry);
  }
  p_hash_map->entries[idx] = NULL;
  if (p_hash_map->current_capacity > 0)
  {
    p_hash_map->current_capacity--;
  }
}