/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_hashmap_utils.c                                 :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/11/07 13:51:48 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:08:32 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_hashmap_private.h"

void	ft_free_hash_element(t_hash_element *elem, t_hashmap *map)
{
	if (map->free_key)
		map->free_key(elem->key);
	if (map->free_value)
		map->free_value(elem->value);
	free(elem);
}

// Helper function to create a new hash element
t_hash_element	*ft_create_hash_element(void *key, void *value, size_t hash)
{
	t_hash_element	*new_element;

	new_element = malloc(sizeof(t_hash_element));
	if (!new_element)
		return (NULL);
	new_element->key = key;
	new_element->value = value;
	new_element->hash = hash;
	return (new_element);
}

//returns 0 for allocation fail without allocating or freeing anything
int	ft_add_hashmap_element(size_t index, t_hashmap *map, t_hash_element *elem)
{
	t_list	*new_node;

	new_node = malloc(sizeof(t_list));
	if (!new_node)
		return (0);
	new_node->content = elem;
	new_node->next = map->table[index];
	map->table[index] = new_node;
	map->nb_elems++;
	return (1);
}

//returns 0 without doing anything if the allocation of the new table fails
//in that case the old table is still valid!
//returns 1 if the resize is a success
int	ft_resize_hashmap(t_hashmap *map)
{
	size_t	new_size;
	t_list	**new_table;

	new_size = map->hashmap_size * HASHMAP_RESIZE_FACTOR;
	new_table = ft_calloc(new_size, sizeof(t_list *));
	if (!new_table)
		return (0);
	ft_copy_hashmap_table(new_table, map->table, new_size, map->hashmap_size);
	free(map->table);
	map->table = new_table;
	map->hashmap_size = new_size;
	return (1);
}
